How to use angular ngIf directive and ngIf else 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 ( * ).

The ngIf directive is used when we want 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 ng-template

<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>

Example of Angular ngIf directive

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 Angular allow us to use ng-template with if/else scenario below example.

An example below we have use *ngIf directive to check odd and even number.

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

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 of 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>

Related posts

Leave a Comment

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

Scroll to Top