Sub topic 2
Showing content conditionally with @if
This chapter covers the @if block: its syntax, how Angular evaluates the condition, what happens to the DOM and to child components when the condition changes, and the mistakes that cause most bugs. It assumes you can write a standalone component with an inline template, use interpolation and event bindings, and read a signal by calling it. @else if, @else, and the as alias have their own chapters. They appear here only where a code example needs them.
What @if does
@if renders a block of template content only when its condition is truthy. When the condition is falsy, Angular does not render the block.
import { Component, signal } from '@angular/core';
@Component({
selector: 'app-banner',
template: `
<button (click)="visible.set(!visible())">Toggle banner</button>
@if (visible()) {
<p class="banner">Maintenance starts at 22:00 UTC.</p>
}
`,
})
export class BannerComponent {
visible = signal(true);
}The syntax has three parts:
- The
@ifkeyword. - A condition in parentheses, written as an ordinary template expression.
- A block in curly braces, containing any template content.
@if is part of the template language itself. You do not import a module, a directive, or NgIf. The compiler recognizes the block directly, which is the main difference from *ngIf. The overview chapter covered why Angular made that choice.
How the condition is evaluated
The condition is a template expression, so the usual rules apply:
- It reads properties and methods of the component class.
- It can use comparison, logical, ternary, and nullish operators.
- It cannot contain assignments,
new, increment operators, or chained statements.
import { Component, signal, computed } from '@angular/core';
@Component({
selector: 'app-cart-notice',
template: `
@if (itemCount() > 0 && !isCheckingOut()) {
<p>You have {{ itemCount() }} item(s) in your cart.</p>
}
@if (hasDiscount()) {
<p>A discount will be applied at checkout.</p>
}
`,
})
export class CartNoticeComponent {
itemCount = signal(3);
isCheckingOut = signal(false);
hasDiscount = computed(() => this.itemCount() >= 3);
}The second block reads a computed signal. Moving non-trivial logic into a computed keeps the template short and lets Angular cache the result until a dependency changes.
Truthiness
@if follows JavaScript truthiness, not a strict check for true. These values are falsy and hide the block:
false0andNaN''(empty string)nullandundefined
Everything else is truthy, including an empty array [] and an empty object {}. That catches people out when they write @if (items()) and expect the block to hide for an empty list.
import { Component, signal } from '@angular/core';
@Component({
selector: 'app-results',
template: `
<!-- Always shows, because [] is truthy -->
@if (results()) {
<p>Results loaded.</p>
}
<!-- Shows only when the array has elements -->
@if (results().length > 0) {
<p>{{ results().length }} result(s) found.</p>
}
`,
})
export class ResultsComponent {
results = signal<string[]>([]);
}State the intent in the condition. Compare .length to a number, or compare to null explicitly, instead of relying on truthiness when the value could legitimately be 0 or ''.
When the condition is re-evaluated
Angular re-evaluates the condition during change detection. If the expression reads signals, Angular tracks them, so the view is refreshed when one of them changes. If it reads plain class properties, it is re-evaluated whenever the component is checked. Angular compares the new result with the previous one by truthiness. If the truthiness did not change, the block is left alone and its bindings update in place.
What happens to the DOM
When an @if condition is false, the content is not in the DOM at all. Angular does not hide it with CSS. It never creates it, or destroys it if it existed.
This has practical consequences:
- Components are created and destroyed. A component inside an
@ifblock is instantiated when the condition becomes true. Its constructor andngOnInitrun each time. When the condition becomes false,ngOnDestroyruns and its state is discarded. - Local state is lost. If the block contains a form input or a child component with its own signals, toggling the condition off and on resets them.
- Queries do not see hidden content. A
viewChild()that targets an element inside a false@ifreturnsundefineduntil the block renders. - Cost matters for heavy content. Creating a large subtree on each toggle is more work than flipping a CSS property.
import { Component, OnDestroy, OnInit, signal } from '@angular/core';
@Component({
selector: 'app-ticker',
template: `<p>Tick: {{ tick() }}</p>`,
})
export class TickerComponent implements OnInit, OnDestroy {
tick = signal(0);
private timer?: ReturnType<typeof setInterval>;
ngOnInit() {
console.log('ticker created');
this.timer = setInterval(() => this.tick.update((t) => t + 1), 1000);
}
ngOnDestroy() {
console.log('ticker destroyed');
clearInterval(this.timer);
}
}
@Component({
selector: 'app-ticker-host',
imports: [TickerComponent],
template: `
<button (click)="show.set(!show())">Toggle ticker</button>
@if (show()) {
<app-ticker />
}
`,
})
export class TickerHostComponent {
show = signal(true);
}Each click that turns the ticker off logs "ticker destroyed" and clears the interval. Turning it back on logs "ticker created" and restarts the count at zero.
When to hide with CSS instead
If you need to keep state, avoid re-creation cost, or animate between states, keep the content in the DOM and toggle a class or style:
<section [class.hidden]="!expanded()">
<app-heavy-chart />
</section>Use @if when the content should not exist, such as when it needs data that is not available yet, or when you want to release its resources. Use CSS when the content should merely be invisible.
Multiple elements and no wrapper
The block body can contain several sibling nodes. Unlike *ngIf, you do not need a wrapper element or <ng-container> to apply a condition to a group.
import { Component, input } from '@angular/core';
@Component({
selector: 'app-user-card',
template: `
<h2>{{ name() }}</h2>
@if (email()) {
<p class="label">Email</p>
<p>{{ email() }}</p>
}
`,
})
export class UserCardComponent {
name = input.required<string>();
email = input<string>('');
}The two <p> elements render together or not at all, and no extra element appears in the DOM. Because @if is not an attribute, you also cannot place it on an element the way you place *ngIf. If you want to condition a single element, put that element inside the block.
Whitespace and literal braces
Because @, {, and } have meaning in templates, you must escape them when you want the literal characters. Use HTML entities:
@for@{for{}for}
import { Component } from '@angular/core';
@Component({
selector: 'app-contact',
template: `
<p>Write to support@example.com</p>
<p>Object syntax looks like { a: 1 }.</p>
`,
})
export class ContactComponent {}An unescaped @ followed by a word can be parsed as the start of a block, and an unmatched } is a compile error. Email addresses in templates are a common trigger.
Common mistakes with @if
| Mistake | What happens | Fix |
|---|---|---|
| `@if (isLoggedIn)` where `isLoggedIn` is a signal | The signal is a function, so it is always truthy and the block always renders | Call it: `@if (isLoggedIn())` |
| `@if (items())` for an array | An empty array is truthy, so the block renders | Test `items().length > 0` |
| Omitting the parentheses or braces | Compile error | Write `@if (cond) { ... }` |
| Using `@if` to protect state that must survive | State is destroyed on each toggle | Hide with CSS, or move the state to a parent or service |
| Putting `@if` on an element like `<div @if="x">` | Not valid syntax | Wrap the element in an `@if` block |
| Assigning in the condition, `@if (x = 3)` | Compile error | Use `===` to compare |
| Unescaped `@` in text | Parsed as a block | Write `@` |
Watch the order of operators
Because the condition is a normal expression, optional chaining and nullish operators work and help with data that arrives late:
import { Component, signal } from '@angular/core';
interface Profile {
address?: { city?: string };
}
@Component({
selector: 'app-location',
template: `
@if (profile()?.address?.city) {
<p>City: {{ profile()?.address?.city }}</p>
}
`,
})
export class LocationComponent {
profile = signal<Profile | null>(null);
}Note that the template repeats the expression inside the block. The compiler does not carry the narrowing from the condition into the expression in the body in this case, because the condition tests a nested optional chain. The alias form, described in a later chapter, removes this repetition.
Comparison with *ngIf
The runtime behavior is the same: content is created or destroyed. The differences are in the syntax and the tooling.
| Aspect | `*ngIf` | `@if` |
|---|---|---|
| Import needed | `NgIf` or `CommonModule` | None |
| Form | Attribute on an element | Block that holds any content |
| Group of siblings | Needs a wrapper or `<ng-container>` | Supported directly |
| Else branch | `else` with an `<ng-template>` reference | `@else { }` block, covered next |
| Implementation | Structural directive in a library | Compiler feature |
If you maintain an older code base, both can coexist in one project and even one template. The migration chapter shows how to convert existing templates automatically.
Exercise
A component has items = signal<string[]>([]). The template contains @if (items()) { <p>You have items.</p> }. The paragraph shows even though the list is empty. Why does this happen, and how would you change the condition so the paragraph shows only when the list has at least one element?
Show answer
An empty array is truthy in JavaScript, so items() evaluates to a truthy value and the block renders. Compare the length instead: @if (items().length > 0) { <p>You have items.</p> }. Calling items() is correct because items is a signal. Without the call, the signal function itself would always be truthy.
Exercise
A page shows <app-video-player /> inside @if (showPlayer()). Users report that the video restarts from the beginning each time they close and reopen the player panel. What causes this, and what alternative would keep the playback position?
Show answer
When showPlayer() becomes false, Angular destroys the player component and its state. When it becomes true again, a new instance is created and starts from the beginning. To keep the position, keep the component in the DOM and hide it with CSS, for example <app-video-player [class.hidden]="!showPlayer()" />. Alternatively, store the playback position in a parent component or a service and restore it when the player is created.