Ir al contenido

Templates & Control Flow

Esta página aún no está disponible en tu idioma.

Angular 18 introduced built-in control flow syntax that replaces structural directives. This is now the only recommended approach — the legacy *ngIf, *ngFor, and *ngSwitch directives are deprecated.


@if (user()) {
<app-user-card [name]="user().name" />
} @else {
<p>No user found.</p>
}

Multiple conditions:

@if (items().length > 10) {
<p>Showing first 10 results.</p>
} @else if (items().length > 0) {
<p>{{ items().length }} results found.</p>
} @else {
<p>No results.</p>
}

@for (user of users(); track user.id) {
<app-user-card [name]="user.name" [email]="user.email" />
} @empty {
<p>No users available.</p>
}

Important: The track expression is required. It helps Angular efficiently identify and update items in the list.

Common track patterns:

<!-- Track by unique identifier (preferred) -->
@for (item of items(); track item.id) { ... }
<!-- Track by index (when no unique ID exists) -->
@for (item of items(); track $index) { ... }
<!-- Track by the item itself (for primitives) -->
@for (name of names(); track name) { ... }

Available implicit variables inside @for:

VariableDescription
$indexCurrent index (0-based)
$firsttrue if this is the first item
$lasttrue if this is the last item
$eventrue if the index is even
$oddtrue if the index is odd
$countTotal number of items in the collection

Example using implicit variables:

@for (user of users(); track user.id) {
<div [class.first]="$first" [class.last]="$last">
<span>{{ $index + 1 }}.</span> {{ user.name }}
</div>
} @empty {
<p>No users to display.</p>
}

@switch (user().role) {
@case ('admin') {
<app-admin-badge />
}
@case ('editor') {
<app-editor-badge />
}
@default {
<app-user-badge />
}
}

Legacy DirectiveModern Syntax
*ngIf="condition"@if (condition) { ... }
*ngIf="condition; else elseRef"@if (condition) { ... } @else { ... }
*ngFor="let item of items; trackBy: trackFn"@for (item of items; track item.id) { ... }
[ngSwitch]="value" / *ngSwitchCase@switch (value) { @case (...) { ... } }