Understanding ngIf, ngIfElse, ngIfThen In Angular

Ng-if

 
Ng-if conditionally includes a template based on the value of the expression.
 
It adds or removes the HTML element in the dom layout.
 
The basic syntax of the Ng-if directives is simple and effective, all we need to do is prefix the directive name with an asterisk(*) and add it anywhere inside our template.
 
Ng-if is a structural directive that can add or remove the host element and its descendants in dom layout at run time. It conditionally shows the inline templates.
 
Ng-if works on the basis of the true and false results of the given expression. If the condition is true the element will be added to the dom layout. Others will be removed.
 
Ng-if.html 
  1. <h1>if Statements in angular </h1>      
  2. <input type="radio" name="radio1" (click)="changevalue(true)" id="rad">true      
  3. <input type="radio" name="radio1" (click)="changevalue(false)" id="rad">false      
  4. <div *ngIf="isvalid">      
  5.     <h3>this is valid</h3>      
  6. </div>      
  7. <div *ngIf="!isvalid">      
  8.     <h3>this is not valid</h3>      
  9. </div>     
Ng-if.ts
  1. import { Component, OnInit } from '@angular/core';    
  2. @Component({    
  3.   selector: 'app-ifelse',    
  4.   templateUrl: './ifelse.component.html',    
  5.   styleUrls: ['./ifelse.component.css']    
  6. })    
  7. export class IfelseComponent{    
  8.   isvalid:boolean=true;    
  9.   changevalue(valid){    
  10.     this.isvalid=valid;    
  11.   }    
  12. }     
module.ts
  1. import { NgModule } from '@angular/core';  
  2. import { BrowserModule } from '@angular/platform-browser';  
  3.   
  4. import { AppRoutingModule } from './app-routing.module';  
  5. import {HttpClientModule } from '@angular/common/http'  
  6. import { AppComponent } from './app.component';  
  7. import { AddComponent } from './add/add.component';  
  8. import { RouterModule, Routes} from '@angular/router';  
  9. import{BookService } from './book.service';  
  10. import {InMemoryWebApiModule } from 'angular-in-memory-web-api';  
  11. import {TestData } from './testdata'  
  12.   
  13. import { FormsModule, ReactiveFormsModule } from '@angular/forms';  
  14. import { ShowdataComponent } from './showdata/showdata.component';  
  15. import { CommonModule } from '@angular/common';  
  16. import { IfelseComponent } from './ifelse/ifelse.component';  
  17. const routes: Routes = [  
  18.   {path:'', component:AddComponent},  
  19.   { path:'add', component:AddComponent}  
  20. ];  
  21.   
  22. @NgModule({  
  23.   declarations: [  
  24.     AppComponent,  
  25.     AddComponent,  
  26.     ShowdataComponent,  
  27.     IfelseComponent  
  28.   ],  
  29.   imports: [  
  30.     BrowserModule,  
  31.     AppRoutingModule,RouterModule.forRoot(routes),ReactiveFormsModule, FormsModule,  
  32.     HttpClientModule, CommonModule,  
  33.     InMemoryWebApiModule.forRoot(TestData)  
  34.   ],  
  35.   providers: [BookService],  
  36.   bootstrap: [IfelseComponent]  
  37. })  
  38. export class AppModule { }  
main.ts
  1. import { enableProdMode } from '@angular/core';    
  2. import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';    
  3. import { AppModule } from './app/app.module';    
  4. import { environment } from './environments/environment';    
  5. if (environment.production) {    
  6.   enableProdMode();    
  7. }  
  8. platformBrowserDynamic().bootstrapModule(AppModule)    
  9.   .catch(err => console.error(err));    
index.html
  1. <!doctype html>    
  2. <html lang="en">    
  3. <head>    
  4.   <meta charset="utf-8">    
  5.   <title>Dhwani</title>    
  6.   <base href="/">    
  7.   <meta name="viewport" content="width=device-width, initial-scale=1">    
  8.   <link rel="icon" type="image/x-icon" href="favicon.ico">    
  9. </head>    
  10. <body>    
  11.   <app-ifelse></app-ifelse>    
  12. </body>    
  13. </html>    
Now run the application using the command " ng serve". After a few seconds you can see that your application will be compiled successfully.
 
Now you have to open the web browser and hit the "local host:4200" after a few seconds your browser will display the output.
 
When you click on the true button the output will be shown like,
 
OUTPUT

 
Now you can see that when you click on the true button the true statements are displayed.
 
When you click on the false button the output will be shown like,
 
OUTPUT
 
 
Now you can see that when you click on the false button the false statements are displayed.
 

Ng-if-else

 
Ng-if with else - else is used when we want to display something or a false condition. The else block is used when there are two conditions and runs one at a time. If else condition is used where two alternatives are checked and the user has an own option.
 
For else block, we need to use <ng-template> element. It is rafters by a template reference variable. If will use that template reference to display else block when the condition is false.
 
Example
 
if-else.html
  1. <h1>if else Statements in angular </h1>    
  2. <input type="radio" name="radio1" (click)="changevalue(true)" id="rad">true    
  3. <input type="radio" name="radio1" (click)="changevalue(false)" id="rad">false    
  4. <div *ngIf="isvalid ; else elseblock">    
  5.     <h3>if else statements is valid</h3>    
  6. </div>    
  7. <ng-template #elseblock>    
  8.     <div>    
  9.         <h3>if else statements is unvalid</h3>    
  10.     </div>    
  11. </ng-template>    
if-else.ts
  1. import { Component, OnInit } from '@angular/core';    
  2. @Component({    
  3.   selector: 'app-ifelse',    
  4.   templateUrl: './ifelse.component.html',    
  5.   styleUrls: ['./ifelse.component.css']    
  6. })    
  7. export class IfelseComponent{    
  8.   isvalid:boolean=true;    
  9.   changevalue(valid){    
  10.     this.isvalid=valid;    
  11.   }    
  12. }     
module.ts
  1. import { NgModule } from '@angular/core';      
  2. import { BrowserModule } from '@angular/platform-browser';      
  3. import { AppRoutingModule } from './app-routing.module';      
  4. import {HttpClientModule } from '@angular/common/http'      
  5. import { AppComponent } from './app.component';      
  6. import { AddComponent } from './add/add.component';      
  7. import { RouterModule, Routes} from '@angular/router';      
  8. import{BookService } from './book.service';      
  9. import {InMemoryWebApiModule } from 'angular-in-memory-web-api';      
  10. import {TestData } from './testdata'      
  11. import { FormsModule, ReactiveFormsModule } from '@angular/forms';      
  12. import { ShowdataComponent } from './showdata/showdata.component';      
  13. import { CommonModule } from '@angular/common';      
  14. import { IfelseComponent } from './ifelse/ifelse.component';      
  15. const routes: Routes = [      
  16.   {path:'', component:AddComponent},      
  17.   { path:'add', component:AddComponent}      
  18. ];      
  19.       
  20. @NgModule({      
  21.   declarations: [      
  22.     AppComponent,      
  23.     AddComponent,      
  24.     ShowdataComponent,      
  25.     IfelseComponent      
  26.   ],      
  27.   imports: [      
  28.     BrowserModule,      
  29.     AppRoutingModule,RouterModule.forRoot(routes),ReactiveFormsModule, FormsModule,      
  30.     HttpClientModule, CommonModule,      
  31.     InMemoryWebApiModule.forRoot(TestData)      
  32.   ],      
  33.   providers: [BookService],      
  34.   bootstrap: [IfelseComponent]      
  35. })      
  36. export class AppModule { }       
main.ts
  1. import { enableProdMode } from '@angular/core';      
  2. import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';      
  3. import { AppModule } from './app/app.module';      
  4. import { environment } from './environments/environment';      
  5. if (environment.production) {      
  6.   enableProdMode();      
  7. }      
  8. platformBrowserDynamic().bootstrapModule(AppModule)      
  9.   .catch(err => console.error(err));       
index.ts
  1. <!doctype html>  
  2. <html lang="en">  
  3. <head>  
  4.   <meta charset="utf-8">  
  5.   <title>Dhwani</title>  
  6.   <base href="/">  
  7.   <meta name="viewport" content="width=device-width, initial-scale=1">  
  8.   <link rel="icon" type="image/x-icon" href="favicon.ico">  
  9. </head>  
  10. <body>  
  11.   <app-ifelse></app-ifelse>  
  12. </body>  
  13. </html>   
Now run the application using the command "ng serve". After few seconds you can see that your application will be compiled successfully.
 
Now you have to open the web browser and hit the "local host:4200" after a few seconds your browser will display the output.
 
When you click on the true button the output will be shown like,
 
OUTPUT
 
 
Now you can see that when you click on the true button the true statements are displayed.
 
When you click on the false button the output will be shown like,
 
OUTPUT
 
 
Now you can see that when you click on the false button the false statements are displayed. 
 

Ng-if else with then block

 
When the condition is true the <ng-template> with reference variable and then the block is executed. And when the condition is false then <ng-template> with reference variable else block is executed. The value of the block and else block can be changed at run time.
 
We can have more than one <ng-template> for then and else block. At run time we can switch to those <ng-template> by changing the value of then-block and else block. At one time only one <ng-template> for then block and else block will run.
 
Ng-if-else-then .html
  1. <h1> using if else with  then Statements in angular </h1>    
  2. <input type="radio" name="radio1" (click)="changevalue(true)" id="rad">true    
  3. <input type="radio" name="radio1" (click)="changevalue(false)" id="rad">false    
  4. <div *ngIf="isvalid ; then thenblock;  else elseblock"></div>    
  5.     <ng-template #thenblock>    
  6.         <div>    
  7.             <h2>this is valid data using then block</h2>    
  8.         </div>    
  9.     </ng-template>    
  10. <ng-template #elseblock>    
  11.     <div>    
  12.         <h2>this is not valid data using then block.</h2>    
  13.     </div>    
  14. </ng-template>     
Ng-if-else-then.ts
  1. import { Component, OnInit } from '@angular/core';    
  2. @Component({    
  3.   selector: 'app-ifelse',    
  4.   templateUrl: './ifelse.component.html',    
  5.   styleUrls: ['./ifelse.component.css']    
  6. })    
  7. export class IfelseComponent{    
  8.   isvalid:boolean=true;    
  9.   changevalue(valid){    
  10.     this.isvalid=valid;    
  11.   }    
  12. }     
module.ts
  1. import { NgModule } from '@angular/core';    
  2. import { BrowserModule } from '@angular/platform-browser';    
  3. import { AppRoutingModule } from './app-routing.module';    
  4. import {HttpClientModule } from '@angular/common/http'    
  5. import { AppComponent } from './app.component';    
  6. import { AddComponent } from './add/add.component';    
  7. import { RouterModule, Routes} from '@angular/router';    
  8. import{BookService } from './book.service';    
  9. import {InMemoryWebApiModule } from 'angular-in-memory-web-api';    
  10. import {TestData } from './testdata'    
  11. import { FormsModule, ReactiveFormsModule } from '@angular/forms';    
  12. import { ShowdataComponent } from './showdata/showdata.component';    
  13. import { CommonModule } from '@angular/common';    
  14. import { IfelseComponent } from './ifelse/ifelse.component';    
  15. const routes: Routes = [    
  16.   {path:'', component:AddComponent},    
  17.   { path:'add', component:AddComponent}    
  18. ];    
  19.     
  20. @NgModule({    
  21.   declarations: [    
  22.     AppComponent,    
  23.     AddComponent,    
  24.     ShowdataComponent,    
  25.     IfelseComponent    
  26.   ],    
  27.   imports: [    
  28.     BrowserModule,    
  29.     AppRoutingModule,RouterModule.forRoot(routes),ReactiveFormsModule, FormsModule,    
  30.     HttpClientModule, CommonModule,    
  31.     InMemoryWebApiModule.forRoot(TestData)    
  32.   ],    
  33.   providers: [BookService],    
  34.   bootstrap: [IfelseComponent]    
  35. })    
  36. export class AppModule { }    
main.ts
  1. import { enableProdMode } from '@angular/core';    
  2. import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';    
  3. import { AppModule } from './app/app.module';    
  4. import { environment } from './environments/environment';    
  5. if (environment.production) {    
  6.   enableProdMode();    
  7. }    
  8. platformBrowserDynamic().bootstrapModule(AppModule)    
  9.   .catch(err => console.error(err));    
index.ts
  1. <!doctype html>      
  2. <html lang="en">      
  3. <head>      
  4.   <meta charset="utf-8">      
  5.   <title>Dhwani</title>      
  6.   <base href="/">      
  7.   <meta name="viewport" content="width=device-width, initial-scale=1">      
  8.   <link rel="icon" type="image/x-icon" href="favicon.ico">      
  9. </head>      
  10. <body>      
  11.   <app-ifelse></app-ifelse>      
  12. </body>      
  13. </html>        
Now run the application using the command " ng serve". After few seconds you can see that your application will be compiled successfully.
 
Now you have to open the web browser and hit the "local host:4200" after a few seconds your browser will display the output.
 
When you click on the true button the output will be shown like,
 
OUTPUT
 
 
Now you can see that when you click on the true button the true statements displayed.
 
When you click on the false button the output will be shown like,
 
OUTPUT 
 
 
Now you can see that when you click on the false button the false statements are displayed. Follow Chaman Gautam to learn more about angular. follow C# Corner to learn more technology.