The “If” evaluates expression
and then renders the “else” or “then” template in its place when
expression is “truthy” or “falsy” respectively.
Then: - This template is the inline template of “If” unless bound to
a different value.
Else: - This template is blank unless it is bound.
Selectors: -
1. If
2. If then
3. If else
The
multiple examples for Angular 4 if else and then as given bellows,
Syntax:-
<element *ngIf="[condition expression]; else [else template]"> </element>
Syntax:-
<div *ngIf="users | async; else loadingGrid; let user"> <p>{{user.Id}}</p> <p>{{user.name}}</p> <p>{{user.Age}}</p> </div> <ng-template #loadingGrid>loading...</ng-template>
Syntax :- We can also use 'then else'
<div *ngIf="isValid;then then_content else other_content">If IsValid then display other</div> <ng-template #then_content>content here...</ng-template> <ng-template #other_content>other content here...</ng-template>
Example 1 as,
<div *ngIf="isValid;else other_content"> <p>Display valid content here ...</p> </div> <ng-template #other_content> <p>Other content here...</p> </ng-template>
Example 2 as,
<div *ngIf="title; then logout else login"></div> <ng-template #login>Please login to continue.</ng-template> <ng-template #logout>Hi Anil!<button>Logout</button>.</ng-template>
Example 3 as,
//our root app component import {Component, NgModule} from '@angular/core' import {BrowserModule} from '@angular/platform-browser' @Component({ selector: 'else-cmp', template: `<button (click)="isValid = !isValid">update</button> <div *ngIf="isValid; else other_content"> content here ... </div> <ng-template #other_content>other content here...</ng-template>`, }) export class ElseComponent { isValid:boolean = true; constructor() { } } @Component({ selector: 'else-then-cmp', template: ` <button (click)="isValid = !isValid">update</button> <div *ngIf="isValid;then content else other_content"></div> <ng-template #content>content here...</ng-template> <ng-template #other_content>other content here...</ng-template> `, }) export class ElseThenComponent { isValid:boolean = true; constructor() { } } @Component({ selector: 'my-app', template: ` <h4>Using else :</h4> <else-cmp></else-cmp> <h4>Using else then:</h4> <else-then-cmp></else-then-cmp> `, }) export class App { isValid:boolean = true; constructor() { } } @NgModule({ imports: [ BrowserModule ], declarations: [ App , ElseComponent, ElseThenComponent], bootstrap: [ App ] }) export class AppModule {}
Stayed Informed - Best Angular 2 Interview Questions and Answers
I hope you are
enjoying with this post! Please share with you friends. Thank you!!