Angular ngIf Directive

Angular ngIf Directive with Then and Else block

In this article, I am going to discuss Angular ngIf Directive with examples. Please read our previous article where we discussed the use of trackBy with ngFor directive with an example. At the end of this article, I am sure, you will definitely understand the need and use of Angular ngIf directive along with else and then block.

Angular ngIf Directive:

The ngIf is a structural directive and it is used to add or removes the HTML element and its descendant elements from the DOM layout at runtime conditionally. That means it conditionally shows the inline template.

The ngIf directive works on the basis of a boolean true and false results of a given expression. If the condition is true, the elements will be added into the DOM layout otherwise they simply removed from the DOM layout.

The basic syntax of the ngIf directive is very simple, all we need to do is prefix the directive name with an asterisk (*) as shown below and add it anywhere inside your template. Here if the given “expression” result is false or null, then the elements HTML element and its descendant elements will not be added to the DOM.

*ngIf = “expression”

Example to understand Angular ngIf Directive:

Please have a look at the following image. As you can, here we have two div Element and we are using the ngIf directive to add or remove the div from the DOM. If the isValid (this is a variable defined in the component class) value is true, then the first div is going to be added into the DOM and if the value is false, then the second div is going to be added into the DOM.

Example to understand Angular ngIf Directive

So, first, modify the app.component.html file as shown below.

<div *ngIf="isValid">
     <b>The Data is valid.</b>
  </div>  

  <div *ngIf="!isValid">
     <b>The Data is invalid.</b>
  </div> 

Then modify the app.component.ts file as shown below.

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

At this moment, change the value of isValid Boolean property (true and false) and check the output in the browser and based on the value, the respective div will be added into the DOM and that you can in the webpage.

Another Example For Better Understanding:

Let us enhance the same example. Now, instead of hardcoding the isValid Boolean property value, we will set this value from the radio buttons. We will create two radio buttons and based on the selected radio button value we will set the IsValid property value. For better understanding please have a look at the below image.

Angular ngIf Directive with Then and Else block

When the Valid radio button is checked, we need to add the first Div to the DOM and when the InValid radio button is checked we need to add the second Div into the DOM. Let’s see how to implement this.

Modify the app.component.ts file:

Please modify the app.component.ts file as shown below. By default, we set the Boolean isvalid property to true. We have also created one method i.e. ChangeData which accepts a Boolean parameter (in this case valid) and then it set the isValid property value with the incoming parameter value (valid).

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

Please modify the app.component.html file as shown below. Here we have created two radio buttons with the name rb. Then we attach our method ChangeData to the click event of the radio button. For the Valid radio button, we are passing true to the ChangeData method and for the Invalid radio button, we are passing false to the ChangeData method.

<div>
    <input type="radio" name="rb" (click)= "ChangeData(true)" checked > Valid
    <input type="radio" name="rb" (click)= "ChangeData(false)"> Invalid
  </div>

  <div *ngIf="isValid">
     <b>The Data is valid.</b>
  </div>  
   
  <div *ngIf="!isValid">
     <b>The Data is invalid.</b>
  </div>

With the above changes in place, now run the application and you should get the output as expected.

Angular NgIf directive with else block:

Like other programming languages such as C, Java, and C#, the else is also used when you want to display something for the false condition of NgIf block. The syntax to use the ngIf block with the else block as follows:

<div *ngIf = “condition; else elseBlock”>…</div>
<ng-template #elseblock>….</ng-tempalte>

Here, for else block you need to use <ng-template> element. It is referred by a template reference variable. NgIf will use that template reference variable to display the else block when the condition is false.

Let us work with the same example. Please have a look at the following image. In the else block we have created a template variable with the name elseblock (you can give any name as per your choice). So, what will happen here is, it will check the ngIf condition and if the condition is true then it will execute if block. On the other hand, if the condition is false, then it will look for the else block. As we created the else block with the name elseblock, so it searches for ng-template tag followed by template variable name (<ng-template #elseblock>) and add that block to the DOM.

Angular NgIf directive with else block

So, modify the app.component.html file as shown below and then see the output in the browser.

<div>
    <input type="radio" name="rb" (click)= "ChangeData(true)" checked > Valid
    <input type="radio" name="rb" (click)= "ChangeData(false)"> Invalid
  </div>

  <div *ngIf="isValid else elseblock">
     <b>The Data is valid.</b>
  </div>  

  <ng-template #elseblock>
    <div >
        <b>The Data is invalid.</b>
     </div> 
  </ng-template>
NgIf with Then and else:

The NgIf with then and else is used as follows. When the condition is true then the <ng-template> with the reference variable then block is executed and when the condition is false then the <ng-template> with the reference variable else block is executed. For better understanding please have a look at the following image.

NgIf with Then and else:

We can have more than one <ng-template> for then and else block and at runtime, we can switch to that ng-template by changing the value of then block and else block. At any given point of time, one ng-template is going to be executed.

So, modify the app.component.html file as shown below and then see the output in the browser.

<div>
    <input type="radio" name="rb" (click)= "ChangeData(true)" checked > Valid
    <input type="radio" name="rb" (click)= "ChangeData(false)"> Invalid
  </div>

  <div *ngIf="isValid then thenblock else elseblock"> </div>

  <ng-template #thenblock>
    <div>
    <b>The is Then Block</b>
   </div>  
  </ng-template>
 

  <ng-template #elseblock>
    <div >
        <b>The is Else Block</b>
     </div> 
  </ng-template>

In the next article, I am going to discuss the Angular NgSwitch directive with some examples. Here, in this article, I try to explain the Angular NgIf directive in Angular with else and then block. I hope you enjoy this article and got some idea of how to use the NgIf directive. In our upcoming articles, we will discuss more complicated and complex examples of NgIf directive.

1 thought on “Angular ngIf Directive”

Leave a Reply

Your email address will not be published. Required fields are marked *