Angular NgIf Example

By Arvind Rai, February 11, 2024
This page will walk through Angular NgIf example. NgIf is a directive that is used to add an element subtree to the DOM on the basis of true value of an expression. If the value of expression is false then the element subtree will be removed from the DOM. To use NgIf we need to prefix it with asterisk (*) as *ngIf. Hiding and displaying element subtree using CSS visibility property is not same as work done by NgIf. CSS visibility property does not remove element subtree from DOM, whereas NgIf removes the element subtree from DOM for false value of expression. CSS visibility property does not physically remove the element subtree when hiding, so it continues to consume resources and memory that will affect the performance. In case of NgIf it physically removes element subtree, so it does not consume resources and memory which in turn results into better performance. NgIf is used with HTML elements as well as component elements.
NgIf is used with HTML elements as follows.
<div *ngIf="isValid"> Data is valid. </div> 
NgIf is used with component elements as follows.
<my-msg *ngIf="emp1" [pname] = "emp1.name"> </my-msg> 
Now find the complete example of NgIf step by step.

Create Component, HTML Template and CSS

Find the component, HTML template and CSS used in our example.
person.component.ts
import {Component} from '@angular/core';
import {NumEnum} from './numEnum';
import {Employee} from './employee';
@Component({
    selector: 'person-app',
    templateUrl: './person.component.html', 
    styleUrls: ['./person.component.css']
})
export class PersonComponent {
    isValid = true;
    ids = [1,2,3,4];	
    myNumEnum = NumEnum;	
    emp1 = new Employee(100, 'Nilesh');
    emp2 : Employee;
} 
person.component.html
<b>NgIf with HTML Elements </b><br/>
<p *ngIf="isValid">
	Data is valid.
</p>
<p *ngIf="!isValid">
	Data is not valid.
</p>

<div *ngFor="let id of ids">
  Id is {{id}}
  <div *ngIf="id%2 == 0">
	<div [ngClass]="'one'">Even Number</div>
  </div> 	
  <div *ngIf="id%2 == 1">
	<div [ngClass]="'two'">Odd Number</div>
  </div> 	
</div>

<br/>

<div *ngIf="myNumEnum.TWO > 1">
	 {{myNumEnum.TWO}} is greater than 1.
</div>
<div *ngIf="myNumEnum.THREE < 2">
	 {{myNumEnum.TWO}} is less than 2.
</div>

<br/>

<div *ngIf="emp1">
  Id:{{emp1.id}} Name: {{emp1.name}}
</div>

<div *ngIf="emp2">
  Id:{{emp2.id}} Name: {{emp2.name}}
</div>

<br/><b>NgIf with Component Elements</b><br/>

<my-msg *ngIf="emp1" [pname] = "emp1.name"> </my-msg>

<my-msg ng-template="ngIf:emp1" [pname] = "emp1.name"> </my-msg>

<ng-template [ngIf]="emp1">
   <my-msg *ngIf="emp1" [pname] = "emp1.name"> </my-msg>
</ng-template> 
person.component.css
.one {
    color: green;
}
.two {
    color: red;
} 

NgIf with HTML Elements

Here we will understand using NgIf with HTML elements. NgIf is an angular directive that is used to add an element subtree for true value of expression. NgIf is used as *ngIf="expression". Here if "expression" value is either false or null, in both cases the element subtree will not be added to DOM. Now find the below code snippet.
<p *ngIf="isValid">
	Data is valid.
</p>
<p *ngIf="!isValid">
	Data is not valid.
</p>  
Here isValid is a component property that has been initialized as follows.
isValid = true;  
Hence the output will be
Data is valid.  
And !isValid will return false, so *ngIf="!isValid" will not add element in DOM.

NgIf with NgFor and NgClass

Here we will discuss how to use NgIf with NgFor and NgClass. Suppose we have two CSS classes as .one and .two. To use it with alternating row using NgIf, we can do it as follows.
<div *ngFor="let id of ids">
  Id is {{id}}
  <div *ngIf="id%2 == 0">
	<div [ngClass]="'one'">Even Number</div>
  </div> 	
  <div *ngIf="id%2 == 1">
	<div [ngClass]="'two'">Odd Number</div>
  </div> 	
</div>  
In the above code snippet ids has been initialized in component as an array of numbers as follows.
ids = [1,2,3,4];  
ngFor will iterate the given array and hence id%2 will return 0 and 1 alternatingly. If the value is 0 then element with CSS class .one will be added to DOM otherwise the element with CSS class .two will be added to DOM.

NgIf with Enum

TypeScript enum can also be used with NgIf. To understand this we are creating an enum as given below.
numEnum.ts
export enum NumEnum {
    ONE = 1,
    TWO = 2,
    THREE = 3
}  
We will import this file in our component as given below.
import {NumEnum} from './numEnum';  
Now we need to create a component property and will assign our NumEnum to it. Find the line of code.
myNumEnum = NumEnum;  
In this way we are ready to use enum with NgIf in our code. Find the code snippet.
<div *ngIf="myNumEnum.TWO > 1">
	 {{myNumEnum.TWO}} is greater than 1.
</div>  
In our enum myNumEnum.TWO has value as 2. So the expression myNumEnum.TWO > 1 will return true. Hence the output will be as follows.
2 is greater than 1.  

NgIf Null Check

For the null value of expression assigned to NgIf, it does not add element tree in DOM. So it is useful while accessing property from object to avoid error. For the demo find the class.
employee.ts
export class Employee {
  constructor(public id: number, public name: string) { 
  }
}  
We will import it in our component as follows.
import {Employee} from './employee';  
Now we will define two variables of class Employee type in our component as given below.
emp1 = new Employee(100, 'Nilesh');
emp2 : Employee;  
Here we will notice that emp1 has been instantiated but emp2 has not been instantiated. Now find the code in HTML template.
<div *ngIf="emp1">
  Id:{{emp1.id}} Name: {{emp1.name}}
</div>
<div *ngIf="emp2">
  Id:{{emp2.id}} Name: {{emp2.name}}
</div>  
In the above code snippet before accessing object property, we are checking it by ngIf. The first ngIf will add the element in DOM but second will not because of null value of emp2. Hence expression {{emp2.id}} and {{emp2.name}} will not execute and no chance of error because of null value of emp2.

NgIf with Component Elements

Here we will use NgIf with component elements. For the demo we are creating a child component as given below.
msg.component.ts
import {Component, Input} from '@angular/core';
@Component({
    selector: 'my-msg',
    template: '<p> Hello {{pname}} </p>'
})
export class MsgComponent {
    @Input() pname : string;
}  
Now find the parent HTML template code snippet with component element from person.component.html.
<my-msg *ngIf="emp1" [pname] = "emp1.name"> </my-msg> 
Here we are performing component property binding and using ngIf. Now if emp1 will be null or undefined, the child component with selector my-msg will not execute.

Find the application component and module of our example.
app.component.ts
import { Component } from '@angular/core';

@Component({
   selector: 'app-root',
   template: `
		  <person-app></person-app>
      `
})
export class AppComponent {
}  
app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { PersonComponent } from './person.component';
import { MsgComponent } from './msg.component';

@NgModule({
    imports: [
        BrowserModule
    ],
    declarations: [
        AppComponent,
        PersonComponent,
        MsgComponent
    ],
    providers: [
    ],
    bootstrap: [
        AppComponent
    ]
})
export class AppModule { } 

Expanding ngIf with ng-template

Here we will understand the expanding *ngIf into template. When we use *ngIf in our code, angular first transform it into template directive and then <template> tag.
Find the use of ngIf with asterisk (*)
<my-msg *ngIf="emp1" [pname] = "emp1.name"> </my-msg> 
ngIf is expanded with ng-template attribute as follows.
<my-msg ng-template="ngIf:emp1" [pname] = "emp1.name"> </my-msg> 
ngIf is expanded <ng-template> tag as follows.
<ng-template [ngIf]="emp1">
   <my-msg *ngIf="emp1" [pname] = "emp1.name"> </my-msg>
</ng-template> 

Angular NgIf-Then-Else

We can also use NgIf with then and else. 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>.

Using 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> 
Using NgIf with Then and Else
then template is 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> 

Output

Find the print-screen of the output.
Angular NgIf Example

Reference

NgIf Directive

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI







©2024 concretepage.com | Privacy Policy | Contact Us