*ngIf directive
- In the world of Angular, the "ngIf" directive are marker on DOM elements (HTML tags) that tells Angular to do something with that element. This directive allows developers to control the visibility of elements in the HTML based on specific conditions.
- The "ngIf" directive is a structural directive in Angular. It's used to add or remove elements from the DOM (Document Object Model) based on a given condition. This condition is typically defined in your Angular component and can be as simple as a boolean variable.
Syntax:
<element *ngIf="condition">
<!-- Content to be displayed when the 'condition' is true -->
</element>
Example:
Step 1: Create an Angular project using Angular CLI.
ng new ng-if-example
Step 2: Create a new component message
ng g c message
Step 3: Edit the 'message.component.html' to use '*ngIf' :
<!-- message.component.html -->
<div>
<h2>Conditional Message Example</h2>
<p *ngIf="showMessage">
This message is displayed when 'showMessage' is true.
</p>
<p *ngIf="!showMessage">
This message is displayed when 'showMessage' is false.
</p>
</div>
Step 4: Edit the 'message.component.ts' to define the component's logic.
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-message',
templateUrl: './message.component.html',
styleUrls: ['./message.component.css']
})
export class MessageComponent implements OnInit {
showMessage: boolean = true;
constructor() { }
ngOnInit() {
}
}
Step 5: Add the <app-message></app-message> to the ‘app.component.html’ to include the ‘message component’ in the main application.
<app-message></app-message>
Step 6: Now run or compile the application.
ng serve
You will see the result on http://localhost:4200