ngIf Directive
Imagine you have a light switch. When you flip it on, the light appears; flip it off, the light disappears. Angular's *ngIf directive works exactly like that – it adds or removes elements from the DOM based on a condition.
The *ngIf directive is a structural directive that conditionally includes a template based on the value of an expression.
Basic syntax:
<div *ngIf="condition">
This content is shown only if condition is true.
</div>
Here's a practical example:
@Component({
selector: 'app-login-status',
template: `
<div *ngIf="isLoggedIn; else loginPrompt">
<p>Welcome back, {{ username }}!</p>
<button (click)="logout()">Logout</button>
</div>
<ng-template #loginPrompt>
<p>Please log in to continue.</p>
<button (click)="login()">Login</button>
</ng-template>
`
})
export class LoginStatusComponent {
isLoggedIn = false;
username = 'JohnDoe';
login() {
this.isLoggedIn = true;
}
logout() {
this.isLoggedIn = false;
}
}
You can also use
then and else with *ngIf:<div *ngIf="isLoggedIn; then welcomeBlock else loginBlock"></div>
<ng-template #welcomeBlock>
<p>Welcome back!</p>
</ng-template>
<ng-template #loginBlock>
<p>Please login.</p>
</ng-template>
Two Minute Drill
- *ngIf conditionally adds/removes elements from DOM.
- Use `else` to show a template when condition is false.
- Use `then` and `else` together for more complex scenarios.
- Elements are completely destroyed/created, not just hidden.
- Great for conditional UI, authentication checks, loading states.
Need more clarification?
Drop us an email at career@quipoinfotech.com
