Angular NgIf-Then-Else Example

By Arvind Rai, February 11, 2024
This page will walk through Angular NgIf-Then-Else example. NgIf conditionally includes a template based on the value of expression. It adds or removes the HTML element in DOM layout. If the expression value is true then NgIf renders the then template in its place and if the expression value is false then NgIf renders the else template in its place. then template is the inline template of NgIf unless bound to a different value and else template is blank unless it is bound. It is not necessary to use then and else with NgIf. In simple way NgIf is used to show conditionally inline template. If condition in NgIf is false and it is necessary to show a template then we use else and its binding point is <ng-template>. Usually then is the inlined template of NgIf but we can change it and make non-inlined using a binding and binding point will be <ng-template>. Because then and else are bindings, the template references can change at runtime. We can also store conditional result in a variable. We can use async pipe for Observable and Promise object. Now we will discuss complete example step by step.

<ng-template> Element

<ng-template> is an Angular element for rendering HTML. It is never displayed directly. Suppose we have following code in our HTML template.
<ng-template>
  <p>Hello World!</p>
</ng-template> 
When the code runs then the code written inside <ng-template> will not be displayed. It writes a comment.
<ng-template> is used by structural directive such as NgIf.

Using NgIf

NgIf is an structural directive that can add or remove host element and its descendants in DOM layout at run time. It conditionally shows the inline template. NgIf works on the basis of true and false result of given expression. If condition is true, the elements will be added into DOM layout otherwise they will be removed. NgIf can be used in different ways.
<div *ngIf="condition">...</div>
<div template="ngIf condition">...</div>
<ng-template [ngIf]="condition"><div>...</div></ng-template> 
Now we will provide an example of NgIf directive.
ngif.component.html
<h3>Using NgIf</h3>
<div>
  <input type="radio" name="rad1" (click)= "changeValue(true)"> True
  <input type="radio" name="rad1" (click)= "changeValue(false)"> False
</div>
<div *ngIf="isValid">
   <b>Data is valid.</b>
</div>   
<div *ngIf="!isValid">
   <b>Data is invalid.</b>
</div> 
In the above code two <div> host element is using NgIf. On the basis of true and false condition, the respective <div> will be added or removed from the DOM. Find the component used in the example.
ngif.component.ts
import { Component } from '@angular/core';

@Component({
     selector: 'app-ngif',
     templateUrl: './ngif.component.html'
})
export class NgIfComponent { 
     isValid: boolean = true;
     age:number = 12;
     changeValue(valid: boolean) {
	this.isValid = valid;
     }
} 
Find the print screen.
Angular NgIf-Then-Else Example

Using NgIf with Else

In this example we will use NgIf with else. In our application else is used when we want to display something for false condition. The else block is used as follows.
<div *ngIf="condition; else elseBlock">...</div>
<ng-template #elseBlock>...</ng-template> 
For else block we need to use <ng-template> element. It is referred by a template reference variable. NgIf will use that template reference variable to display else block when condition is false. The <ng-template> element can be written anywhere in the HTML template but it will be readable if we write it just after host element of NgIf. In the false condition, the host element will be replaced by the body of <ng-template> element. Now find the example of NgIf with else.
ngif-else.component.html
<h3>Using NgIf with Else</h3>
<b>Example-1:</b><br/><br/>
<div>
  <input type="radio" name="rad2" (click)= "changeValue(true)"> True
  <input type="radio" name="rad2" (click)= "changeValue(false)"> False
</div>
<div *ngIf="isValid; else elseBlock">
   <b>Data is valid.</b>
</div>   
<ng-template #elseBlock>
  <div>
   <b>Data is invalid.</b>
  </div> 
</ng-template>

<br/><b>Example-2:</b><br/><br/>
<div>Enter Age:	<input type="text" [(ngModel)] = 'age'> </div> <br/>
<div *ngIf="age < 18; else elseAgeBlock">
   <b>Not eligible to vote.</b>
</div>   
<ng-template #elseAgeBlock>
   <b>Eligible to vote.</b>
</ng-template> 
In the above code, we are using two examples of NgIf directive. When condition is true, the host element with its descendants will be added in DOM layout and if condition is false then <ng-template> code block will run in the place of host element. Now Find the component used in our example.
ngif-else.component.ts
import { Component } from '@angular/core';

@Component({
     selector: 'app-ngif-else',
     templateUrl: './ngif-else.component.html'
})
export class NgIfElseComponent { 
     isValid: boolean = true;
     age:number = 12;
     changeValue(valid: boolean) {
	this.isValid = valid;
     }
} 
Find the print screen.
Angular NgIf-Then-Else Example

Using NgIf with Then and Else

In this example we will use NgIf with then and else. then template is the inline template of NgIf and when it is bound to different value then it displays <ng-template> body having template reference value as then value. NgIf with then and else is used as follows.
<div *ngIf="condition; then thenBlock else elseBlock"></div>
<ng-template #thenBlock>...</ng-template>
<ng-template #elseBlock>...</ng-template> 
When condition is true, then the <ng-template> with reference variable thenBlock is executed and when condition is false then the <ng-template> with reference variable elseBlock is executed. The value of thenBlock and elseBlock can be changed at run time. We can have more than one <ng-template> for then and else block and at runtime we can switch to those <ng-template> by changing the value of thenBlock and elseBlock. At one time only one <ng-template> for thenBlock or elseBlock will run. Now find the example.
ngif-then-else.component.html
<h3>Using NgIf with Then and Else</h3>
<b>Example-1:</b><br/><br/>
<div>
  <input type="radio" name="rad3" (click)= "changeValue(true)"> True
  <input type="radio" name="rad3" (click)= "changeValue(false)"> False
</div>
<div *ngIf="isValid; then thenBlock; else elseBlock"> </div>
<ng-template #thenBlock>
  <div>   <b>Data is valid.</b>   </div> 
</ng-template>
<ng-template #elseBlock>
  <div>   <b>Data is invalid.</b>   </div> 
</ng-template>

<br/><b>Example-2:</b><br/><br/>
<div>Enter Age:	<input type="text" [(ngModel)] = 'age'> </div> <br/>
<div>
  <button type="button" (click)= "toggleThenBlock()"> Toggle Then Block </button>
  <button type="button" (click)= "toggleElseBlock()"> Toggle Else Block </button>
</div>
<br/>
<div *ngIf="age > 17; then myThenBlock; else myElseBlock"> </div>
<ng-template #firstThenBlock>
  <div>   <b>First Then Block: Eligible to vote.</b>   </div> 
</ng-template>
<ng-template #secondThenBlock>
  <div>   <b>Second Then Block Block: Eligible to vote.</b>   </div> 
</ng-template>

<ng-template #firstElseBlock>
   <div> <b>First Else Block: Not eligible to vote</b>   </div> 
</ng-template>
<ng-template #secondElseBlock>
   <div> <b>Second Else Block: Not eligible to vote</b>   </div> 
</ng-template> 
We have created two scenarios to use NgIf with then and else. In the first scenario we have one <ng-template> for then and one <ng-template> for else block. In the second scenario we have more than one <ng-template> for then and more than one <ng-template> for else block. But at one time only one <ng-template> will run. In the second scenario we have buttons to change the value of then and else binding point. Now find the component used in the example.
ngif-then-else.component.ts
import { Component, ViewChild, TemplateRef, OnInit } from '@angular/core';

@Component({
   selector: 'app-ngif-then-else',
   templateUrl: './ngif-then-else.component.html'
})
export class NgIfThenElseComponent implements OnInit { 
	 isValid: boolean = true;	
	 age:number = 12;		 
	 myThenBlock: TemplateRef<any> = null;
	 myElseBlock: TemplateRef<any> = null;	
	 
	 @ViewChild('firstThenBlock')
	 firstThenBlock: TemplateRef<any> = null;
	 @ViewChild('secondThenBlock')
	 secondThenBlock: TemplateRef<any> = null;	
	 
	 @ViewChild('firstElseBlock')
         firstElseBlock: TemplateRef<any> = null;
         @ViewChild('secondElseBlock')
         secondElseBlock: TemplateRef<any> = null;
	 
	 ngOnInit() {
	   this.myThenBlock = this.firstThenBlock;
	   this.myElseBlock = this.firstElseBlock;
	 }
	 changeValue(valid: boolean) {
	   this.isValid = valid;
	 }
	 toggleThenBlock() {
	   this.myThenBlock = this.myThenBlock === this.firstThenBlock ? this.secondThenBlock : this.firstThenBlock; 
	 }
	 toggleElseBlock() {
	   this.myElseBlock = this.myElseBlock === this.firstElseBlock ? this.secondElseBlock : this.firstElseBlock;
	 }
} 
Using @ViewChild decorator we get the instance of TemplateRef for a given template reference variable. In the toggleThenBlock() we are switching the value of then and in the toggleElseBlock() we are switching the value of else. Find the print screen.
Angular NgIf-Then-Else Example

Using NgIf with Async Pipe

In this example we will use NgIf with AsyncPipe. We can store conditional result in a variable. This approach is useful when initially the value is null or undefined and we want to avoid exception. As we know that to avoid exception we can access value of an object using safe-traversal operator ?. and these types of scenarios arise when we fetch value over HTTP. Before getting the HTTP response the object may be undefined or null. In case of NgIf Angular provides better approach to handle exception without using safe-traversal operator ?.
Now simply to store conditional result in a variable, we can do as follows without using async.
<div *ngIf="condition as value; else elseBlock">{{value}}</div>
<ng-template #elseBlock>...</ng-template> 
If we have Observable or Promise object and we want to avoid exception for undefined object then we need to use async pipe as given below.
<div *ngIf="userObservable | async as user; else loading">
     {{user.name}}
</div>
<ng-template #loading>Loading message...</ng-template> 
If userObservable is undefined or null then else block will execute and body of <ng-template> will be displayed. Once userObservable gets value then that value will be stored in user variable and {{user.name}} will execute.
Now find the example. In our example we have a Promise object that will be used by NgIf with async pipe.
ngif-async.component.html
<h3>Using NgIf with AsyncPipe</h3>

<div *ngIf="promiseMsg | async as message; else loading">
	 <b>{{message}}</b>
</div>   
<ng-template #loading>Loading message...</ng-template> 
Find the component used in the example.
ngif-async.component.ts
import { Component, OnInit } from '@angular/core';

import { MessageService } from './message.service';

@Component({
   selector: 'app-ngif-async',
   templateUrl: './ngif-async.component.html'
})
export class NgIfAsyncComponent implements OnInit { 
   promiseMsg: Promise<string>;
   constructor(private messageService: MessageService) { }
   ngOnInit(): void {
	this.promiseMsg = this.messageService.getMessageSlowly();
   }
} 
Find the service used in the example.
message.service.ts
import { Injectable } from '@angular/core';

@Injectable()
export class MessageService {
    getMessageSlowly(): Promise<string> {
	    let message = 'Hello World!';
             return new Promise(resolve => {
            // Delay by 3 second
            setTimeout(() => resolve(message), 3000);
        });
    }	
} 
Find the print screen.
Angular NgIf-Then-Else Example

Application Component and Module

app.component.ts
import { Component } from '@angular/core';

@Component({
   selector: 'app-root',
   template: `  
                <app-ngif></app-ngif>   
                <app-ngif-else></app-ngif-else>
		<app-ngif-then-else></app-ngif-then-else>								
		<app-ngif-async></app-ngif-async>
             `
})
export class AppComponent { 

} 
app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';

import { AppComponent }  from './app.component';
import { NgIfComponent }  from './ngif.component';
import { NgIfElseComponent }  from './ngif-else.component';
import { NgIfThenElseComponent }  from './ngif-then-else.component';
import { NgIfAsyncComponent }  from './ngif-async.component';
import { MessageService } from './message.service';

@NgModule({
  imports: [     
        BrowserModule,
	FormsModule
  ],
  declarations: [
        AppComponent,
	NgIfComponent,
	NgIfAsyncComponent,
	NgIfElseComponent,
	NgIfThenElseComponent
  ],
  providers: [
        MessageService
  ],
  bootstrap: [
        AppComponent
  ]
})
export class AppModule { } 
Find the print-screen of the output.
Angular NgIf-Then-Else Example

Reference

NgIf DIRECTIVE

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI







©2024 concretepage.com | Privacy Policy | Contact Us