*ngIf directive
In Angular, the *ngIf directive is like a smart switch for your HTML.
It lets you:
Think of it as telling Angular:
It is called a structural directive because it changes the structure of your web page by adding or removing elements from the DOM.
It lets you:
- Show elements if a condition is true
- Hide elements if the condition is false
Think of it as telling Angular:
“Only display this part if this condition is true.”
It is called a structural directive because it changes the structure of your web page by adding or removing elements from the DOM.
Syntax:
<element *ngIf="condition"> <!-- This content is shown only when 'condition' is true --></element>
Here:
Example: Using ngIf in Angular
Step 1: Create a New Angular Project
- condition - usually a variable from your TypeScript component
- When the condition is true - element is added to the page
- When the condition is false - element is removed from the page
Example: Using ngIf in Angular
Step 1: Create a New Angular Project
ng new ng-if-example
Step 2: Generate a Component
ng g c message
Step 3: Add ngIf in the Component Template
Edit 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>
Here, we display two different messages based on the value of showMessage.
Step 4: Add Logic in the Component
Edit message.component.ts
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; // Change to false to see the other message constructor() { }
ngOnInit() {}}
Step 5: Include the Component in Your App
In app.component.html
<app-message></app-message>
Step 6: Run the App
ng serve
Open your browser at:
http://localhost:4200
This message is displayed when 'showMessage' is true.