Open In App

Angular 10 NgIf Directive

Improve
Improve
Like Article
Like
Save
Share
Report

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:

  • CommonModule

 

Selectors:

  • [ngIf]

Approach: 

  • Create an Angular app to be used.
  • There is no need for any import for the NgIf to be used.
  • In app.component.ts define the variable for which condition is to be checked with ngIf directive.
  • In app.component.html use NgIf directive with conditions to be checked.
  • Serve the angular app using ng serve to see the output.

Example 1:

app.component.ts




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


app.component.html




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


Output:

Example 2:

Javascript




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


app.component.html




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


Output:

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



Last Updated : 03 Jun, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads