[angular] How to use *ngIf else?

I'm using Angular and I want to use *ngIf else (available since version 4) in this example:

<div *ngIf="isValid">
  content here ...
</div>

<div *ngIf="!isValid">
 other content here...
</div>

How can I acheive the same behavior with ngIf else ?

This question is related to angular if-statement angular-template

The answer is


Here's some nice and clean syntax on Angular's NgIf and using the else statement. In short, you will declare an ElementRef on an element and then reference it in the else block:

<div *ngIf="isLoggedIn; else loggedOut">
   Welcome back, friend.
</div>

<ng-template #loggedOut>
  Please friend, login.
</ng-template>

I've taken this example from NgIf, Else, Then which I found to be really well explained.

It also demonstrates using the <ng-template> syntax:

<ng-template [ngIf]="isLoggedIn" [ngIfElse]="loggedOut">
  <div>
    Welcome back, friend.
  </div>
</ng-template>

<ng-template #loggedOut>
  <div>
    Please friend, login.
  </div>
</ng-template>

And also using <ng-container> if that's what you're after:

<ng-container
  *ngIf="isLoggedIn; then loggedIn; else loggedOut">
</ng-container>

<ng-template #loggedIn>
  <div>
    Welcome back, friend.
  </div>
</ng-template>
<ng-template #loggedOut>
  <div>
    Please friend, login.
  </div>
</ng-template>

Source is taken from here on Angular's NgIf and Else syntax. I hope this helped! Enjoy.


Just add new updates from Angular 8.

  1. For case if with else, we can use ngIf and ngIfElse.
<ng-template [ngIf]="condition" [ngIfElse]="elseBlock">
  Content to render when condition is true.
</ng-template>
<ng-template #elseBlock>
  Content to render when condition is false.
</ng-template>
  1. For case if with then, we can use ngIf and ngIfThen.
<ng-template [ngIf]="condition" [ngIfThen]="thenBlock">
  This content is never showing
</ng-template>
<ng-template #thenBlock>
  Content to render when condition is true.
</ng-template>
  1. For case if with then and else, we can use ngIf, ngIfThen, and ngIfElse.
<ng-template [ngIf]="condition" [ngIfThen]="thenBlock" [ngIfElse]="elseBlock">
  This content is never showing
</ng-template>
<ng-template #thenBlock>
  Content to render when condition is true.
</ng-template>
<ng-template #elseBlock>
  Content to render when condition is false.
</ng-template>

There are two possibilities to use if condition on HTML tag or templates:

  1. *ngIf directive from CommonModule, on HTML tag;
  2. if-else

enter image description here


You can also use Javascript short ternary conditional operator ? in angular like this:

{{doThis() ? 'foo' : 'bar'}}

or

<div [ngClass]="doThis() ? 'foo' : 'bar'">

ngif expression resulting value won’t just be the boolean true or false

if the expression is just a object, it still evaluate it as truthiness.

if the object is undefined, or non-exist, then ngif will evaluate it as falseness.

common use is if an object loaded, exist, then display the content of this object, otherwise display "loading.......".

 <div *ngIf="!object">
     Still loading...........
 </div>

<div *ngIf="object">
     <!-- the content of this object -->

           object.info, object.id, object.name ... etc.
 </div>

another example:

  things = {
 car: 'Honda',
 shoes: 'Nike',
 shirt: 'Tom Ford',
 watch: 'Timex'
 };

 <div *ngIf="things.car; else noCar">
  Nice car!
 </div>

<ng-template #noCar>
   Call a Uber.
</ng-template>

 <!-- Nice car ! -->

anthoer example:

<div *ngIf="things.car; let car">
   Nice {{ car }}!
 </div>
<!-- Nice Honda! -->

ngif template

ngif angular 4


In Angular 4.0 if..else syntax is quite similar to conditional operators in Java.

In Java you use to "condition?stmnt1:stmnt2".

In Angular 4.0 you use *ngIf="condition;then stmnt1 else stmnt2".


You can Use <ng-container> and <ng-template> for Achieve This

<ng-container *ngIf="isValid; then template1 else template2"></ng-container>

<ng-template #template1>
     <div>Template 1 contains</div>
</ng-template>

<ng-template #template2>
     <div>Template 2 contains </div>
</ng-template>

You can find the Stackblitz Live demo below

live demo

Hope This will helps ... !!!


<div *ngIf="show; else elseBlock">Text to show</div>
<ng-template #elseBlock>Alternate text while primary text is hidden</ng-template>

To work with observable, this is what I usually do to display if the observable array consists of data.

<div *ngIf="(observable$ | async) as listOfObject else emptyList">
   <div >
        ....
    </div>
</div>
 <ng-template #emptyList>
   <div >
        ...
    </div>
</ng-template>

In Angular 4.x.x You 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.

"bindEmail" it will check email is available or not. if email is exist than Logout will show otherwise Login will show

<li *ngIf="bindEmail;then logout else login"></li>
<ng-template #logout><li><a routerLink="/logout">Logout</a></li></ng-template>
<ng-template #login><li><a routerLink="/login">Login</a></li></ng-template>

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>

Syntax for ngIf/Else

<div *ngIf=”condition; else elseBlock”>Truthy condition</div>
<ng-template #elseBlock>Falsy condition</ng-template>

enter image description here

Using NgIf / Else/ Then explicit syntax

To add then template we just have to bind it to a template explicitly.

<div *ngIf=”condition; then thenBlock else elseBlock”> ... </div> 
<ng-template #thenBlock>Then template</ng-template>
<ng-template #elseBlock>Else template</ng-template>

enter image description here

Observables with NgIf and Async Pipe

For more details

enter image description here


<div *ngIf="this.model.SerialNumber != '';then ConnectedContent else DisconnectedContent" class="data-font">    </div>

<ng-template #ConnectedContent class="data-font">Connected</ng-template>
<ng-template #DisconnectedContent class="data-font">Disconnected</ng-template>

In Angular 4, 5 and 6

We can simply create a template reference variable [2] and link that to the else condition inside an *ngIf directive

The possible Syntaxes [1] are:

<!-- Only If condition -->
<div *ngIf="condition">...</div>
<!-- or -->
<ng-template [ngIf]="condition"><div>...</div></ng-template>


<!-- If and else conditions -->
<div *ngIf="condition; else elseBlock">...</div>
<!-- or -->
<ng-template #elseBlock>...</ng-template>

<!-- If-then-else -->
<div *ngIf="condition; then thenBlock else elseBlock"></div>
<ng-template #thenBlock>...</ng-template>
<ng-template #elseBlock>...</ng-template>


<!-- If and else conditions (storing condition value locally) -->
<div *ngIf="condition as value; else elseBlock">{{value}}</div>
<ng-template #elseBlock>...</ng-template>

DEMO: https://stackblitz.com/edit/angular-feumnt?embed=1&file=src/app/app.component.html

Sources:

  1. https://angular.io/api/common/NgIf#syntax
  2. https://angular.io/guide/template-syntax#template-reference-variables--var-

ng-template

<ng-template [ngIf]="condition1" [ngIfElse]="template2">
        ...
</ng-template>


<ng-template #template2> 
        ...
</ng-template>

I know this has been a while, but want to add it if it helps. The way I went about with is to have two flags in the component and two ngIfs for the corresponding two flags.

It was simple and worked well with material as ng-template and material were not working well together.


Examples related to angular

error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class error TS1086: An accessor cannot be declared in an ambient context in Angular 9 TS1086: An accessor cannot be declared in ambient context @angular/material/index.d.ts' is not a module Why powershell does not run Angular commands? error: This is probably not a problem with npm. There is likely additional logging output above Angular @ViewChild() error: Expected 2 arguments, but got 1 Schema validation failed with the following errors: Data path ".builders['app-shell']" should have required property 'class' Access blocked by CORS policy: Response to preflight request doesn't pass access control check origin 'http://localhost:4200' has been blocked by CORS policy in Angular7

Examples related to if-statement

How to use *ngIf else? SQL Server IF EXISTS THEN 1 ELSE 2 What is a good practice to check if an environmental variable exists or not? Using OR operator in a jquery if statement R multiple conditions in if statement Syntax for an If statement using a boolean How to have multiple conditions for one if statement in python Ifelse statement in R with multiple conditions If strings starts with in PowerShell Multiple conditions in an IF statement in Excel VBA

Examples related to angular-template

How and where to use ::ng-deep? How to use *ngIf else? Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays Dynamic tabs with user-click chosen components Getting reference to child component in parent component How to use Angular2 templates with *ngFor to create a table out of nested arrays? What is the equivalent of ngShow and ngHide in Angular 2+? Angular: conditional class with *ngClass