Directives: ngIf, ngFor, ngClass
Site Admin
· 11 Sep 2026
· 8 views
Directives: ngIf, ngFor, ngClass
Structural directives change the shape of the DOM, and attribute directives change the look and behavior of elements. The built-in ones cover the most common needs.
ngIf for conditionals
Render a block only when a condition is true:
<p *ngIf="isLoggedIn">Welcome back</p>
You can attach an else template:
<p *ngIf="isLoggedIn; else guest">Welcome</p>
<ng-template #guest><p>Please log in</p></ng-template>
ngFor to repeat
Loop over an array and render one block per item:
<li *ngFor="let product of products">
{{ product.name }}
</li>
You can capture the index or the element:
<li *ngFor="let product of products; let i = index">
{{ i + 1 }}. {{ product.name }}
</li>
ngClass for dynamic styles
ngClass toggles CSS classes based on conditions:
<div [ngClass]="{
'active': selected.id === item.id,
'muted': item.disabled
}">{{ item.name }}</div>
Keys are class names and values are booleans. When a value turns true, Angular adds the class; when false, it removes it.
ngStyle for inline styles
ngStyle works like ngClass but for inline CSS properties:
<p [ngStyle]="{ color: price > 100 ? 'red' : 'green' }">Status</p>
Key Points
- ngIf adds or removes elements from the DOM.
- ngFor repeats a block for each array item.
- Capture index and element with let variables.
- ngClass toggles CSS classes from conditions.
- ngStyle sets inline styles dynamically.