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 conditions in the html file.
Implement Process:-
Step1:- Declare Boolean variable in the app.component.ts file
Example:- Suppose, you have a showTitle Boolean variable that has the 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>
Step 3:- Now, if the condition matches then show the title otherwise not.
Note:- If you define showTitle as false then does not show data on the browser.
else condition implementation:- when you use the 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 a 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 uses two Boolean variables and match any one condition that is true.
Example:- if you have two Boolean variables a and b and match any one condition is true.
<div *ngIf="a || b">
<h1>Employees Management Tools</h1>
</div>
AND Operator:- It basically used two Boolean variables and matched both conditions.
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>