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
- <h1>if Statements in angular </h1>
- <input type="radio" name="radio1" (click)="changevalue(true)" id="rad">true
- <input type="radio" name="radio1" (click)="changevalue(false)" id="rad">false
- <div *ngIf="isvalid">
- <h3>this is valid</h3>
- </div>
- <div *ngIf="!isvalid">
- <h3>this is not valid</h3>
- </div>
Ng-if.ts
- import { Component, OnInit } from '@angular/core';
- @Component({
- selector: 'app-ifelse',
- templateUrl: './ifelse.component.html',
- styleUrls: ['./ifelse.component.css']
- })
- export class IfelseComponent{
- isvalid:boolean=true;
- changevalue(valid){
- this.isvalid=valid;
- }
- }
module.ts
- import { NgModule } from '@angular/core';
- import { BrowserModule } from '@angular/platform-browser';
-
- import { AppRoutingModule } from './app-routing.module';
- import {HttpClientModule } from '@angular/common/http'
- import { AppComponent } from './app.component';
- import { AddComponent } from './add/add.component';
- import { RouterModule, Routes} from '@angular/router';
- import{BookService } from './book.service';
- import {InMemoryWebApiModule } from 'angular-in-memory-web-api';
- import {TestData } from './testdata'
-
- import { FormsModule, ReactiveFormsModule } from '@angular/forms';
- import { ShowdataComponent } from './showdata/showdata.component';
- import { CommonModule } from '@angular/common';
- import { IfelseComponent } from './ifelse/ifelse.component';
- const routes: Routes = [
- {path:'', component:AddComponent},
- { path:'add', component:AddComponent}
- ];
-
- @NgModule({
- declarations: [
- AppComponent,
- AddComponent,
- ShowdataComponent,
- IfelseComponent
- ],
- imports: [
- BrowserModule,
- AppRoutingModule,RouterModule.forRoot(routes),ReactiveFormsModule, FormsModule,
- HttpClientModule, CommonModule,
- InMemoryWebApiModule.forRoot(TestData)
- ],
- providers: [BookService],
- bootstrap: [IfelseComponent]
- })
- export class AppModule { }
main.ts
- import { enableProdMode } from '@angular/core';
- import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
- import { AppModule } from './app/app.module';
- import { environment } from './environments/environment';
- if (environment.production) {
- enableProdMode();
- }
- platformBrowserDynamic().bootstrapModule(AppModule)
- .catch(err => console.error(err));
index.html
- <!doctype html>
- <html lang="en">
- <head>
- <meta charset="utf-8">
- <title>Dhwani</title>
- <base href="/">
- <meta name="viewport" content="width=device-width, initial-scale=1">
- <link rel="icon" type="image/x-icon" href="favicon.ico">
- </head>
- <body>
- <app-ifelse></app-ifelse>
- </body>
- </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,
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
- <h1>if else Statements in angular </h1>
- <input type="radio" name="radio1" (click)="changevalue(true)" id="rad">true
- <input type="radio" name="radio1" (click)="changevalue(false)" id="rad">false
- <div *ngIf="isvalid ; else elseblock">
- <h3>if else statements is valid</h3>
- </div>
- <ng-template #elseblock>
- <div>
- <h3>if else statements is unvalid</h3>
- </div>
- </ng-template>
if-else.ts
- import { Component, OnInit } from '@angular/core';
- @Component({
- selector: 'app-ifelse',
- templateUrl: './ifelse.component.html',
- styleUrls: ['./ifelse.component.css']
- })
- export class IfelseComponent{
- isvalid:boolean=true;
- changevalue(valid){
- this.isvalid=valid;
- }
- }
module.ts
- import { NgModule } from '@angular/core';
- import { BrowserModule } from '@angular/platform-browser';
- import { AppRoutingModule } from './app-routing.module';
- import {HttpClientModule } from '@angular/common/http'
- import { AppComponent } from './app.component';
- import { AddComponent } from './add/add.component';
- import { RouterModule, Routes} from '@angular/router';
- import{BookService } from './book.service';
- import {InMemoryWebApiModule } from 'angular-in-memory-web-api';
- import {TestData } from './testdata'
- import { FormsModule, ReactiveFormsModule } from '@angular/forms';
- import { ShowdataComponent } from './showdata/showdata.component';
- import { CommonModule } from '@angular/common';
- import { IfelseComponent } from './ifelse/ifelse.component';
- const routes: Routes = [
- {path:'', component:AddComponent},
- { path:'add', component:AddComponent}
- ];
-
- @NgModule({
- declarations: [
- AppComponent,
- AddComponent,
- ShowdataComponent,
- IfelseComponent
- ],
- imports: [
- BrowserModule,
- AppRoutingModule,RouterModule.forRoot(routes),ReactiveFormsModule, FormsModule,
- HttpClientModule, CommonModule,
- InMemoryWebApiModule.forRoot(TestData)
- ],
- providers: [BookService],
- bootstrap: [IfelseComponent]
- })
- export class AppModule { }
main.ts
- import { enableProdMode } from '@angular/core';
- import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
- import { AppModule } from './app/app.module';
- import { environment } from './environments/environment';
- if (environment.production) {
- enableProdMode();
- }
- platformBrowserDynamic().bootstrapModule(AppModule)
- .catch(err => console.error(err));
index.ts
- <!doctype html>
- <html lang="en">
- <head>
- <meta charset="utf-8">
- <title>Dhwani</title>
- <base href="/">
- <meta name="viewport" content="width=device-width, initial-scale=1">
- <link rel="icon" type="image/x-icon" href="favicon.ico">
- </head>
- <body>
- <app-ifelse></app-ifelse>
- </body>
- </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
- <h1> using if else with then Statements in angular </h1>
- <input type="radio" name="radio1" (click)="changevalue(true)" id="rad">true
- <input type="radio" name="radio1" (click)="changevalue(false)" id="rad">false
- <div *ngIf="isvalid ; then thenblock; else elseblock"></div>
- <ng-template #thenblock>
- <div>
- <h2>this is valid data using then block</h2>
- </div>
- </ng-template>
- <ng-template #elseblock>
- <div>
- <h2>this is not valid data using then block.</h2>
- </div>
- </ng-template>
Ng-if-else-then.ts
- import { Component, OnInit } from '@angular/core';
- @Component({
- selector: 'app-ifelse',
- templateUrl: './ifelse.component.html',
- styleUrls: ['./ifelse.component.css']
- })
- export class IfelseComponent{
- isvalid:boolean=true;
- changevalue(valid){
- this.isvalid=valid;
- }
- }
module.ts
- import { NgModule } from '@angular/core';
- import { BrowserModule } from '@angular/platform-browser';
- import { AppRoutingModule } from './app-routing.module';
- import {HttpClientModule } from '@angular/common/http'
- import { AppComponent } from './app.component';
- import { AddComponent } from './add/add.component';
- import { RouterModule, Routes} from '@angular/router';
- import{BookService } from './book.service';
- import {InMemoryWebApiModule } from 'angular-in-memory-web-api';
- import {TestData } from './testdata'
- import { FormsModule, ReactiveFormsModule } from '@angular/forms';
- import { ShowdataComponent } from './showdata/showdata.component';
- import { CommonModule } from '@angular/common';
- import { IfelseComponent } from './ifelse/ifelse.component';
- const routes: Routes = [
- {path:'', component:AddComponent},
- { path:'add', component:AddComponent}
- ];
-
- @NgModule({
- declarations: [
- AppComponent,
- AddComponent,
- ShowdataComponent,
- IfelseComponent
- ],
- imports: [
- BrowserModule,
- AppRoutingModule,RouterModule.forRoot(routes),ReactiveFormsModule, FormsModule,
- HttpClientModule, CommonModule,
- InMemoryWebApiModule.forRoot(TestData)
- ],
- providers: [BookService],
- bootstrap: [IfelseComponent]
- })
- export class AppModule { }
main.ts
- import { enableProdMode } from '@angular/core';
- import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
- import { AppModule } from './app/app.module';
- import { environment } from './environments/environment';
- if (environment.production) {
- enableProdMode();
- }
- platformBrowserDynamic().bootstrapModule(AppModule)
- .catch(err => console.error(err));
index.ts
- <!doctype html>
- <html lang="en">
- <head>
- <meta charset="utf-8">
- <title>Dhwani</title>
- <base href="/">
- <meta name="viewport" content="width=device-width, initial-scale=1">
- <link rel="icon" type="image/x-icon" href="favicon.ico">
- </head>
- <body>
- <app-ifelse></app-ifelse>
- </body>
- </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.