Wednesday, April 1, 2020

Angular ngIf Directive With Examples

Angular provides some of the built-in directives to perform the most common tasks in web application development. Angular ngIf directive is used to conditionally include or remove an element in the HTML document.

If the expression used with the ngIf directive evaluates to true, element is included in the DOM if expression evaluates to false then the element is removed from the DOM.

Here are some examples of ngIf directive-

1. <div *ngIf="true"></div>

Element is always displayed.

2. <div *ngIf="false"></div>

Element is never displayed.

3. <div *ngIf="x > y"></div>

Element is displayed if x is greater than y.

4. <div *ngIf="myFunc()"></div>

Element is displayed if myFunc returns true.


ngIf is a structural directive

As you would have seen in the above examples, asterisk (*) precedes the ngIf directive attribute which means it is a structural directive.

Structural directives are responsible for HTML layout. They change the DOM's structure, typically by adding, removing, or manipulating elements.

Internally Angular translates the *ngIf attribute into a <ng-template> element. If you have a statement as given below

<div *ngIf="user" class="name">{{user.name}}</div>

It is translated into a <ng-template> element, wrapped around the host element, like this.

<ng-template [ngIf]="user">
  <div class="name">{{user.name}}</div>
</ng-template>

Angular ngIf example to display element

In the component there is a boolean flag and the element is displayed in the template based on whether the boolean flag is true or false.

app.component.ts

import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  toggle : boolean = true;
}

app.component.html

<div class="container">
  <div class="row">
    <div class="col-xs-12">
      <p *ngIf="toggle">This text is displayed conditionally using ngIf</p>
    </div>
  </div>
</div>

If you see in the above example value of the toggle boolean variable is not changed once it is assigned. You can add a button to toggle the display.

import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  toggle : boolean = true;
  
  onClickToggle(){
    this.toggle = !this.toggle;
  }
}

Now there is a onClickToggle() function where the value of the toggle variable is reversed.

<div class="container">
  <div class="row">
    <div class="col-xs-12">
      <button class="btn btn-primary" 
        (click)="onClickToggle()">
        Display
      </button>
      <p *ngIf="toggle">This text is displayed conditionally using ngIf</p> 
    </div>
  </div>
</div>

Now the paragraph is removed when the button is clicked and it appears again when the button is clicked again.

Comparison (===) using ngIf

You can also use ngIf for comparing variables, if comparison returns true element is displayed otherwise it is not displayed.

In the component there is a string variable and the element is displayed in the template based on whether the string variable has the certain value or not.

app.component.ts

import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  show : String;
  constructor(){
    this.show = "yes";
  }
}

app.component.html

<div class="container">
  <div class="row">
    <div class="col-xs-12">
      <p *ngIf="show === 'yes'">This text is displayed conditionally using ngIf</p>
    </div>
  </div>
</div>

Angular ngIf to check if object exists

You can also use ngIf to check if object exists before trying to access its fields.

For example you are trying to display name property of the user when no User instance is initialized.

<p><label>Name: </label> {{user.name}} </p>

If you want to display the element only if user instance exists then you can use ngIf to do a check.

<p ngIf="user"><label>Name: </label> {{user.name}} </p>

Here is the complete example.

User Model class

export class User {
  name : string;
  age : number;
  joinDate : Date;
  constructor(name: string, age : number, joinDate : Date) {
    this.name = name;
    this.age = age;
    this.joinDate  = joinDate;
  }
}

app.component.ts

import { Component } from '@angular/core';
import { User } from './user/user.model';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  user : User;
  constructor(){
    // creating user instance
    this.user = new User('Jack', 56, new Date('2005-03-25'));
  }
}

In the component class User class is imported and in the constructor a new instance is also created.

app.component.html

<div class="container">
  <div class="row">
    <div class="col-xs-12">
      <p *ngIf="user"><label>Name: </label> {{user.name}} </p>      
    </div>
  </div>
</div>

The ngIf directive doesn't hide elements with CSS. It adds and removes them physically from the DOM. You can confirm it by inspecting the DOM.

Angular ngIf Directive

Now you can comment the user instance in the constructor.

ngIf Directive example

As you can see now the whole element is removed from the DOM.

ngIf with else

You can also have an else block with if making it if-else conditional statement where if block is executed when the conditional expression resolves to true and else block is executed if expression is false.

Here is an example of the template with ngIf–else

<div class="container">
  <div class="row">
    <div class="col-xs-12">
      <div *ngIf="show; else elseBlock">This text is displayed when condition is true</div>
      <ng-template #elseBlock>This text is displayed when condition is false.</ng-template>
    </div>
  </div>
</div>

As you can see a local reference #elseBlock is placed with <ng-template> which is used to mark a location in DOM.

app.component.ts

import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  show : boolean;

  constructor(){
    this.show = true;
  }
}

ngIf with then and else

Though not used that commonly but you can also have both then and else block with ngIf. Then part is executed if the condition is true, else block is executed otherwise.

<div *ngIf="show; then thenBlock else elseBlock"></div>
<ng-template #thenBlock>This text is displayed when condition is true.</ng-template>
<ng-template #elseBlock>This text is displayed when condition is false.</ng-template>

That's all for this topic Angular ngIf Directive With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Angular Tutorial Page


Related Topics

  1. Angular ngSwitch Directive With Examples
  2. Angular Project Structure With File Description
  3. Angular Application Bootstrap Process
  4. Angular First App - Hello world Example
  5. Angular @Component Decorator

You may also like-

  1. Service in Angular With Examples
  2. Angular Example to Render Multiple Rows
  3. Angular @Input and @Output Example
  4. Core Java Basics Interview Questions And Answers
  5. ConcurrentHashMap in Java
  6. New Date And Time API in Java 8
  7. Magic Methods in Python With Examples
  8. Dependency Injection in Spring Framework