Home  >  Angular 2

Angular 2 NgIf Example

By Arvind Rai, November 17, 2016 | Modified on May 08, 2017
This page will walk through angular 2 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 using TypeScript.

Software Used

Find the software used in our demo.
1. Angular 2.3.0
2. TypeScript 2.0.10
3. Node.js 4.6.0
4. NPM 3.10.8
5. Firefox 50.1.0

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: 'app/person.component.html', 
    styleUrls: ['app/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 template="ngIf:emp1" [pname] = "emp1.name"> </my-msg>

<template [ngIf]="emp1">
   <my-msg *ngIf="emp1" [pname] = "emp1.name"> </my-msg>
</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. To read more about component property binding, go the link Angular 2 Property Binding Example. Now if emp1 will be null or undefined, the child component with selector my-msg will not execute.

Expanding *ngIf into 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> 
First *ngIf will be expanded into template directive by angular as follows.
<my-msg template="ngIf:emp1" [pname] = "emp1.name"> </my-msg> 
Now template directive will be expanded into <template> tag by angular as follows.
<template [ngIf]="emp1">
   <my-msg *ngIf="emp1" [pname] = "emp1.name"> </my-msg>
</template>   

We can directly use ngIf with template directive or <template> tag in place of asterisk (*) in our code if we want.

Angular 4 NgIf-Then-Else

Angular 4 has introduced 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 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> 
Find the link for complete detail.

Angular 4 NgIf-Then-Else Example

Create Module, Main and index.html using TypeScript


module.ts
import {NgModule}        from '@angular/core';
import {BrowserModule}   from '@angular/platform-browser';
import {PersonComponent} from './person.component';
import {MsgComponent}    from './msg.component';
@NgModule({
  imports:      [BrowserModule],
  declarations: [PersonComponent, MsgComponent],
  bootstrap:    [PersonComponent]
})
export class AppModule { } 
main.ts
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
import {AppModule} from './module';
const platform = platformBrowserDynamic();
platform.bootstrapModule(AppModule);  
index.html
<html>
  <head>
    <title>Angular 2 Demo</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="node_modules/core-js/client/shim.min.js"></script>
    <script src="node_modules/zone.js/dist/zone.js"></script>
    <script src="node_modules/reflect-metadata/Reflect.js"></script>
    <script src="node_modules/systemjs/dist/system.src.js"></script>
    <!-- Configure SystemJS -->
    <script src="systemjs.config.js"></script>
    <script>
      System.import('myApp').catch(function(err){ console.error(err); });
    </script>
  </head>
  <body>
    <person-app>Please Wait...</person-app>
  </body>
</html> 

Run Application

Find the steps to run the example.
1. Install Node.js and NPM in the system if not already installed. Make sure that Node.js version must be 4.x.x or higher and NPM version must be 3.x.x or higher.
2. Download the source code using download link given below in the example.
3. Go to the root folder of the project using command prompt and run npm install command.
4. Now run npm start command.
5. Now run index.html file. Find the print screen of the output.
Angular 2 NgIf Example

Reference

ANGULAR 2 TEMPLATE SYNTAX: NgIf

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS
comments powered by Disqus








Copyright ©2017 concretepage.com, all rights reserved |Privacy Policy | Contact Us