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.x You can use ngIf in four way to achieve simple if else procedure:
Just Use If
<div *ngIf="isValid"> If isValid is true </div>
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>
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>
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.
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>