Sub topic 2
Showing content conditionally with @if
This chapter assumes you know basic TypeScript, how to write an Angular component with an inline template, and how to use interpolation and event binding. Familiarity with signals helps, because the examples use them.
What @if does
@if is a built-in template block. It evaluates an expression and renders its contents only when the result is truthy. When the result is falsy, Angular removes that content from the page. You don't import anything to use it. The block is part of the template syntax itself, so it works in any component.
The syntax is the keyword, a condition in parentheses, and a body in braces:
import { Component, signal } from '@angular/core';
@Component({
selector: 'app-session',
template: `
@if (isLoggedIn()) {
<p>Welcome back!</p>
<button (click)="isLoggedIn.set(false)">Log out</button>
} @else {
<button (click)="isLoggedIn.set(true)">Log in</button>
}
`,
})
export class SessionComponent {
isLoggedIn = signal(false);
}The component starts logged out, so only the "Log in" button exists in the page. Clicking it sets the signal to true. Angular re-evaluates the condition, removes the button, and creates the welcome paragraph and the "Log out" button. The @else branch is covered in the next chapter. Here it only shows that @if can have an alternative.
How the condition is evaluated
The condition is an ordinary template expression. It can read signals, component properties, and call methods. Angular follows normal JavaScript truthiness. false, 0, '', null, and undefined hide the content. Objects, non-empty strings, and non-zero numbers show it. An empty array is truthy, so @if (items) shows its content even when items has no elements. Use @if (items.length) instead.
When the condition reads a signal, Angular re-checks it whenever that signal changes. Content is created or destroyed only when the result crosses between truthy and falsy. A change from one truthy value to another leaves the existing content in place and updates its bindings.
Differences from *ngIf
@if replaces the *ngIf directive, but it works differently in a few ways:
- It needs no import, while
*ngIfrequiresNgIforCommonModulein the component'simports. - It adds no wrapper element or attribute to the page.
*ngIfattaches to a host element or anng-template. - The alternative is written as an
@elseblock. You don't need a separateng-templatewith a template reference. - It is built into the compiler, so it needs no directive class at runtime.
Content is removed, not hidden
When the condition turns falsy, Angular destroys everything inside the block. This includes child components and their state. When the condition turns truthy again, Angular creates new instances. A form component inside an @if loses what the user typed when the block closes. If you must keep state, hide the element with a class or the hidden attribute instead, or store the state in a service or a parent component.
Common errors
- Forgetting to call a signal.
@if (isLoggedIn)tests the signal function itself, which is always truthy. Write@if (isLoggedIn()). - Using the old syntax.
<div *ngIf="ok">still works if you importNgIf, but it is a different mechanism. Don't mix*ngIfand@ifon the same condition. - Testing an empty array directly. As noted above,
[]is truthy. Check.length. - Writing a literal
@in template text. The compiler reads@as the start of a block. To show the character, write@. - Missing braces. The body must be in
{ }, even for a single element.
Summary of the model
An @if block is a conditional view. Angular keeps it in the page while its condition is truthy, and it re-checks the condition whenever a signal or other bound value changes.
Exercise
A component has items = signal<string[]>([]) and the template contains @if (items()) { <p>Items found</p> }. Why does "Items found" appear even though the list is empty, and how do you fix it?
Show answer
An empty array is truthy in JavaScript, so the condition passes. Change the condition to @if (items().length), which is 0 (falsy) for an empty list.