How to use *ngIf else? How to use *ngIf else? angular angular

How to use *ngIf else?


Angular 4 and 5:

using else :

<div *ngIf="isValid;else other_content">    content here ...</div><ng-template #other_content>other content here...</ng-template>

you can also use then else :

<div *ngIf="isValid;then content else other_content">here is ignored</div>    <ng-template #content>content here...</ng-template><ng-template #other_content>other content here...</ng-template>

or then alone :

<div *ngIf="isValid;then content"></div>    <ng-template #content>content here...</ng-template>

Demo :

Plunker

Details:

<ng-template>: is Angular’s own implementation of the <template> tag which is according to MDN :

The HTML <template> element is a mechanism for holding client-side content that is not to be rendered when a page is loaded but may subsequently be instantiated during runtime using JavaScript.


In Angular 4.x.xYou can use ngIf in four way to achieve simple if else procedure:

  1. Just Use If

    <div *ngIf="isValid">    If isValid is true</div>
  2. Using If with Else (Please notice to templateName)

    <div *ngIf="isValid; else templateName">    If isValid is true</div><ng-template #templateName>    If isValid is false</ng-template>
  3. Using If with Then (Please notice to templateName)

    <div *ngIf="isValid; then templateName">    Here is never showing</div><ng-template #templateName>    If isValid is true</ng-template>
  4. Using If with Then and Else

    <div *ngIf="isValid; then thenTemplateName else elseTemplateName">    Here is never showing</div><ng-template #thenTemplateName>    If isValid is true</ng-template><ng-template #elseTemplateName>    If isValid is false</ng-template>

Tip: ngIf evaluates the expression and then renders the then or else template in its place when expression is truthy or falsy respectively. Typically the:

  • then template is the inline template of ngIf unless bound to a different value.
  • else template is blank unless it is bound.


For Angular 9/8

Source Link with Examples

    export class AppComponent {      isDone = true;    }

1) *ngIf

    <div *ngIf="isDone">      It's Done!    </div>    <!-- Negation operator-->    <div *ngIf="!isDone">      It's Not Done!    </div>

2) *ngIf and Else

    <ng-container *ngIf="isDone; else elseNotDone">      It's Done!    </ng-container>    <ng-template #elseNotDone>      It's Not Done!    </ng-template>

3) *ngIf, Then and Else

    <ng-container *ngIf="isDone;  then iAmDone; else iAmNotDone">    </ng-container>    <ng-template #iAmDone>      It's Done!    </ng-template>    <ng-template #iAmNotDone>      It's Not Done!    </ng-template>