Open In App

Angular 10 NgIf Directive

In this article, we are going to see what is NgIf in Angular 10 and how to use it.

The ngIf Directive in Angular10 is used to remove or recreate a portion of HTML element based on an expression. If the expression inside it is false then the element is removed and if it is true then the element is added to the DOM.



Syntax:

<li *ngIf='condition'></li>

NgModule: Module used by NgIf is:



 

Selectors:

Approach: 

Example 1:




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




<div *ngIf = 'myBool'>Boolean is set to true</div>

Output:

Example 2:




import { Component, Inject } from '@angular/core';
import { PLATFORM_ID } from '@angular/core';
import { isPlatformWorkerApp } from '@angular/common';
  
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  variab = 10;
}




<div *ngIf = 'variab==1; else multi'>{{variab}}</div>
  
<ng-template #multi>
    {{variab *2}}
  </ng-template>

Output:

Reference: https://angular.io/api/common/NgIf


Article Tags :