Angular *ngIf Directive

Angular *ngIf Directive comes under the Structure Directive and it is used to based on conditional statement. *ngIf Directive is used in the component.html file to display data or not based on the condition.

Syntax:-


 *ngIf="element"

Note:- Basically *ngIf is used to show or hide condition in the html file.

Implement Process:-

Step1:- Declare Boolean variable in the app.component.ts file

Example :- Suppose you have a showTitle Boolean variable which has value true in the app.component.ts file


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

Step2:- Now, conditional statement implemented in the app.component.html file through *ngIf


<div *ngIf="showTitle">
    <h1>Employees Management Tools</h1>
</div>

Step3:- Now, if the condition is match then show the title otherwise not.

Note:- If you define showTitle is false then does not show data on the browser.

else condition implementation:- when you use else condition in the *ngIf Directive then should use ng-template


<div *ngIf="showTitle; else notShowTitle">
    <h1>Employees Management Tools</h1>
</div>

<ng-template #notShowTitle>
  <div>
    Title is not showing(showTitle is false)
  </div>
</ng-template>

Logical Operator

You can implement logical operator in the *ngIf directive

Not Operator:- This condition is used when you match the value false.


<div *ngIf="!showTitle">
    <h1>Employees Management Tools</h1>
</div>

meaning of this condition that showTitle is false then show content.

OR Operator:- it is basically used two Boolean variable and match any one condition is true.

Example:- if you have two Boolean variable a and b and match any one condition is true.


<div *ngIf="a || b">
    <h1>Employees Management Tools</h1>
</div>

AND Operator:- it is basically used two Boolean variable and match both condition.

Example:- If you have two Boolean variables a and b and match both conditions are true


<div *ngIf="a && b">
    <h1>Employees Management Tools</h1>
</div>