*ngIf helps you show or hide parts of your webpage based on conditions. It makes your app smarter by only displaying what is needed.
0
0
*ngIf for conditional rendering in Angular
Introduction
Show a login button only when the user is not logged in.
Display a loading spinner while data is being fetched.
Hide a form after it is submitted successfully.
Show error messages only when there is an error.
Syntax
Angular
<div *ngIf="condition">Content to show if true</div>
The *ngIf directive uses a condition inside quotes.
If the condition is true, Angular shows the element; if false, it removes it from the page.
Examples
Shows the welcome message only if
isLoggedIn is true.Angular
<p *ngIf="isLoggedIn">Welcome back!</p>Shows the login button only if
isLoggedIn is false.Angular
<button *ngIf="!isLoggedIn">Login</button>Shows the message only if the
items array is not empty.Angular
<div *ngIf="items.length > 0">You have items in your list.</div>
Sample Program
This component shows a welcome message and a button to toggle login status. It uses *ngIf to show different messages depending on whether isLoggedIn is true or false.
Angular
import { Component } from '@angular/core'; @Component({ selector: 'app-root', template: ` <h1>Welcome to the app!</h1> <button (click)="toggleLogin()">Toggle Login</button> <p *ngIf="isLoggedIn">You are logged in.</p> <p *ngIf="!isLoggedIn">Please log in to continue.</p> ` }) export class AppComponent { isLoggedIn = false; toggleLogin() { this.isLoggedIn = !this.isLoggedIn; } }
OutputSuccess
Important Notes
Using *ngIf removes or adds elements from the DOM, which can improve performance.
Remember to use parentheses for event binding like (click) to change conditions.
Summary
*ngIf shows or hides elements based on a condition.
It helps create dynamic and responsive user interfaces.
Use it to control what users see depending on app state.