How to use angular ngIf directive and ngIf else directive .?

The angular, we can control the display of blocks of elements with the help of the Angular ngIf directive. Angular has a lot of built-in directives: ngIf, ngFor, ngSwitch, ngClass , and ngStyle .
The first three directives are called structural directives, which are used to transform the DOM’s structure by adding or removing elements to DOM. Structural directives start with an asterisk ( * ).

What is Angular ngIf directive

Angular directives are used by the component templates, but they may change the output of templates in different ways. The Angular ngIf directive is a structure directive like ngFor and ngSwitch. These directives change the DOM structure.

We have another type of directive called non-structure directives or attribute directives, mostly used to change DOM element appearance.

We used the ngIf structure directive to display or hide an element based on a boolean condition. The condition is determined by the result of the expression that we pass into the directive. If the result of the expression returns a false value, the element will be removed from the DOM.

Angular ngIf directive syntax

An angular ngIf directive adds and removes elements in the DOM, based on the Boolean result of an expression. The *ngIf syntax:

<div *ngIf="condition">
   Render content when condition is true.
</div>

The ng-template directive allows us to run a set of HTML tag blocks based on ngIf|else condition. This directive is useful for showing or hiding a section of the component.

The syntax of Angular ngIf directive

<ng-container *ngIf="condition; else #conditionFalse"> 
   Render content when condition is true
</ng-container>
<ng-template #conditionFalse>
	Render content when condition is false
</ng-template>

Angular ngIf example

We can pass different expressions on the ngIf directive, if the condition is true then, it will add an element inside ngIf to the DOM element. Here we had a few examples we can use.

<div *ngIf="a > b">
....
</div>
<div *ngIf="country.name == 'India'">
  ....
</div>
<div *ngIf="methodOne()">
.... // Run when methodOne return true
</div>

In the example below, we will demonstrate two examples on Angular *ngIf directive

  1. We will display the div element content on a page only when if the condition showMore variable is true.
  2. We can display the div element content through a toggle button.
angular *ngIf example

Add the following line of app.component.html


<h3>Hello everyone !</h3>
<h3>My name is {{ emp.fname }} {{ emp.lname }}</h3>
<button (click)="moreInfo()">More Details</button>

<div *ngIf="showMore === true">
  <h3>I live in {{ emp.city}}</h3>
</div>
<button (click)="showDiv = !showDiv">Toggle Me</button>

<div *ngIf="showDiv" style="color:white; background-color:blue; width:25%">
  Content 1
</div>
<div *ngIf="showDiv" style="color:white; background-color:red; width:25%">
  Content 2
</div>

Add the following line of app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  public emp = {fname: 'Happy', lname: 'Singh', city: 'Delhi'};

  public showMore = false;

  moreInfo(){
    this.showMore = true;
  }
}

In Angular allow us to use ng-template with if/else scenario below example.

In the example below we have used the angular ngIf directive to check odd and even numbers.

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
  <div *ngFor="let number of numbers">
    <div *ngIf="number % 2 == 0; else showOdd">
      Even number <span class="even">{{ number }}</span>
    </div>
    <ng-template #showOdd>
      Odd number <span class="odd">{{ number }}</span>
    </ng-template>
  </div>`,
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  numbers: number[] = [1, 2, 3, 4, 5, 6, 7, 8];
}
angular ngIf directive
Angular ngIf else example on even and odd number

TemplateRef is the class name and is the HTML tag — they are both referencing the same thing. We can use it with ngFor, ngIf, and ngSwitch. Using TemplateRef and ViewContainerRef we can reuse the code in our HTML template. example with ngFor is as follows.

<ng-template ngFor let-person [ngForOf]= "allPersons" let-i="index">
<p>{{i + 1}}. {{person.name}} : {{person.age}} </p>
</ng-template>

Angular template form validate using *ngIf directive

We had demonstrated a few examples of the ngIf directive, last we’ll demonstrate an example of the ngIf directive to show Angular template form validation. Here is a screenshot of our example.

Angular ngIf directive in form
<div class="container">
  <h4> Angular template form validation using ngIf directive </h4>
  <form #profileForm="ngForm" (ngSubmit)="profileForm.form.valid && onSubmit(profileForm.value)">

    <div class="form-group">
      <label>Site name </label>
      <input type="text" name="name" class="form-control" [(ngModel)]="user.name" 
        pattern="[a-z, A-Z, ' ']*" minlength="10" required>
      <p class="text-danger"
        *ngIf="profileForm.controls.name && (profileForm.controls.name.valid || 
         (profileForm.controls.name.touched))">
        Name is required with min length of 10 of alphabet character or white space
      </p>
    </div>

    <div class="form-group">
      <label>Email : </label>
      <input type="email" name="email" class="form-control" 
        pattern="[a-z0-9._%+-][email protected][a-z0-9.-]+\.[a-z]{2,4}$"
        [(ngModel)]="user.email" required>
      <div class="text-danger" *ngIf="profileForm.controls.name && 
          profileForm.controls.email.touched">
        <p *ngIf="profileForm.controls.email.errors?.required">
         Email is a required field!
        </p>
        <p *ngIf="profileForm.controls.email.errors?.pattern">
          This is not a valid Email!!!
        </p>
      </div>
    </div>
    <button class="btn btn-primary float-right" type="submit">
      Submit
    </button>
  </form>

  <div *ngIf="profileForm.valid">{{profileForm.value | json }}</div>
</div>

We have used the ngIf directive on form element control to check is valid and touched. Based on form control status check using ngIf we show messages.

import { Component } from '@angular/core';
import { NgForm } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  user: any;

  constructor() { }

  ngOnInit() {
    this.user = { name: '', email: '' };
  }

  onSubmit(form: NgForm) {
    console.log(form);
  }
}

Conclusion
We have learned the
Angular ngIf directive and demonstrated a few examples of it with and with else conditions. I hope you got some idea of how we can use this directive.

Related posts

Spread the love

Leave a Comment

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

Scroll to Top