Directives, Pipes & Templates
Angular ngIf Directive
*ngIf adds or removes an element from the DOM based on a condition. It does not hide the element with CSS — when the condition is false the element and its component are destroyed entirely.
What is ngIf Directive in Angular?
*ngIf adds or removes an element from the DOM based on a condition. It does not hide the element with CSS — when the condition is false the element and its component are destroyed entirely.
ngIf Directive example
<div *ngIf="jobs.length > 0; else empty">
<app-job-card *ngFor="let job of jobs" [job]="job" />
</div>
<ng-template #empty>
<p>No internships match your filters.</p>
</ng-template>
<!-- store an async result to avoid multiple subscriptions -->
<div *ngIf="user$ | async as user">
Welcome, {{ user.name }}
</div>How this works
The as syntax stores the resolved value in a template variable, which is essential with the async pipe — without it, every reference would create a separate subscription.
Key points to remember
- Removing an element destroys its component state; use [hidden] or CSS when you need to keep it.
- One element can carry only one structural directive — nest or use ng-container.
- The modern equivalent is @if, which needs no CommonModule import.
Common mistakes with ngIf Directive
- Putting *ngIf and *ngFor on the same element, which is a compile error.
- Expecting an *ngIf element to retain scroll position or form state after toggling.
- Forgetting CommonModule in a standalone component, so *ngIf is not recognised.
Angular ngIf Directive— Interview Questions & FAQs
What is the difference between ngIf and hidden?+
*ngIf removes the element from the DOM and destroys the component. [hidden] leaves it in the DOM with display: none, keeping its state. Use ngIf for expensive content, hidden for frequent toggles that must remember state.
