Directives (*ngIf & *ngFor)
Directives add custom behaviors to elements. Structural directives modify DOM layouts by adding or removing elements, while attribute directives change look behaviors.
1 Structural vs Attribute Directives
Directives fall into three main categories:
- Structural Directives: Demarcated with an asterisk (*). They dynamically alter the DOM structure (e.g.
*ngIffor conditional renders,*ngForfor iterating items lists). - Attribute Directives: Modify look details or styles of an existing element (e.g.
[ngClass],[ngStyle]). - Custom Directives: Created with the
@Directivedecorator to add custom event listeners and styling directly to DOM nodes.
2 Listing items and conditionals in code
Let's check structural loops and conditional directives:
HTML — Directives Example
<!-- Conditional rendering -->
<div *ngIf="items.length > 0; else noItems">
<h4>Active Inventory:</h4>
<!-- List Iteration with index and trackBy -->
<ul>
<li *ngFor="let item of items; let idx = index; trackBy: trackById"
[ngClass]="{'highlight': item.isFeatured}">
{{ idx + 1 }}. {{ item.name }}
</li>
</ul>
</div>
<ng-template #noItems>
<p>Inventory is currently empty.</p>
</ng-template>
Using trackBy inside *ngFor optimizes performance by telling Angular how to track updates to specific items (typically by ID), preventing unnecessary re-renders of the entire list.
3 Code Challenge
Challenge: Write a component containing an array of task objects (each with a
name and completed boolean flag). Loop through tasks, using [ngStyle] to display completed tasks in green with a line-through decoration.