FresherTechnicalAngular
What does @if do in an Angular template and how does it replace *ngIf?
Try answering first
Model answer
@if is the built-in control flow block that renders its content only when a condition is truthy. It is part of the template syntax, so you do not import anything. It replaces the older *ngIf directive, which needed NgIf in imports.
@if (user(); as u) {
<p>Hello {{ u.name }}</p>
} @else if (loading()) {
<p>Loading...</p>
} @else {
<p>Please sign in</p>
}
Compared with *ngIf:
@else ifand@elseblocks are part of the syntax, so you no longer needelseplus a template reference variable.askeeps the evaluated value in a local variable.- The compiler handles it directly, which gives better type checking and less runtime code.
New code should use @if. You will still meet *ngIf in older projects, and a schematic (ng generate @angular/core:control-flow) can migrate it.
Prefer @if for new templates.
Key points
- @if is built-in syntax and needs no import
- @else if and @else are part of the block
- as stores the evaluated value
- *ngIf is older syntax with a migration schematic
Likely follow-ups
- Why must @for have a track expression?
Common mistakes
- Writing *ngIf in a new component without importing NgIf