Sub topic 4
Keeping an expression result with as
This chapter assumes you can write a standalone Angular component with an inline template. It also assumes you know the basic @if and @else syntax from the earlier chapters. Familiarity with signals and with RxJS observables helps, because most real uses of as involve one of them.
By the end you will be able to do four things:
- Bind the result of an
@ifcondition to a name. - Explain why this matters for the
asyncpipe. - Use the alias to get a narrowed type.
- Avoid the cases where the alias hides content you wanted to show.
What the alias does
An @if block evaluates a condition and renders its content when the result is truthy. Sometimes the condition is also a value you want to use inside the block. Without an alias, you have to evaluate the same expression a second time.
import { Component, signal } from '@angular/core';
interface User {
name: string;
email: string;
}
@Component({
selector: 'app-greeting',
template: `
@if (user(); as u) {
<h2>{{ u.name }}</h2>
<p>{{ u.email }}</p>
} @else {
<p>Nobody is signed in.</p>
}
`,
})
export class GreetingComponent {
user = signal<User | null>({ name: 'Ada', email: '[email protected]' });
}The syntax is @if (expression; as name). Angular evaluates expression once. If the result is truthy, it stores the result in name and renders the block. Inside the block, u is an ordinary template variable, so you can use it in interpolations, bindings, and nested blocks.
The semicolon is required. @if (user() as u) is a syntax error, because the alias is a separate clause and not part of the expression.
How the evaluation flows
The diagram shows what Angular does each time change detection reaches the block.
The main use: one subscription with the async pipe
The async pipe subscribes to an observable and returns its latest value. Each async pipe in a template creates its own subscription. If you write the pipe twice, you subscribe twice.
For a cold observable, such as one returned by HttpClient, each subscription starts a separate request. The next example makes this visible by logging every subscription.
import { Component } from '@angular/core';
import { AsyncPipe } from '@angular/common';
import { Observable, defer, of } from 'rxjs';
interface User {
name: string;
}
@Component({
selector: 'app-profile',
imports: [AsyncPipe],
template: `
@if (user$ | async) {
<h2>{{ (user$ | async)?.name }}</h2>
}
`,
})
export class ProfileComponent {
user$: Observable<User> = defer(() => {
console.log('subscribed');
return of({ name: 'Ada' });
});
}This template logs subscribed twice. The condition subscribes once, and the interpolation subscribes again. With a real HTTP call you would send two requests. The data in the two places can also disagree if the server answers differently.
The fix is to subscribe once and keep the result:
import { Component } from '@angular/core';
import { AsyncPipe } from '@angular/common';
import { Observable, defer, of } from 'rxjs';
interface User {
name: string;
}
@Component({
selector: 'app-profile',
imports: [AsyncPipe],
template: `
@if (user$ | async; as user) {
<h2>{{ user.name }}</h2>
} @else {
<p>Loading profile...</p>
}
`,
})
export class ProfileComponent {
user$: Observable<User> = defer(() => {
console.log('subscribed');
return of({ name: 'Ada' });
});
}Now subscribed appears once. The @else branch also gives you a loading state. Before the observable emits, the pipe returns null, which is falsy, so the loading message shows. After the first emission, the block renders with user bound to the emitted value.
The ordering matters when you read the syntax. The pipe belongs to the expression, so it comes before the semicolon. The alias comes after it.
The alias narrows the type
The alias has another benefit that applies to signals as well. In the example above, user$ | async has the type User | null. Inside the block, user has the type User, because the block only renders when the value is truthy. You can write user.name without a non-null assertion or an optional chain, and strict template type checking accepts it.
This matters most with signals. A signal is read by calling it, and TypeScript does not narrow the result of a function call between two separate calls. Consider this template:
import { Component, signal } from '@angular/core';
interface User {
name: string;
}
@Component({
selector: 'app-name-tag',
template: `
@if (user()) {
<p>{{ user().name }}</p>
}
`,
})
export class NameTagComponent {
user = signal<User | null>(null);
}With strict templates enabled, the compiler reports that user() is possibly null inside the block. Each user() is a fresh call, and TypeScript cannot know the second call returns the same value as the first. Aliasing fixes it, because u is a plain variable and TypeScript can narrow it:
@if (user(); as u) {
<p>{{ u.name }}</p>
}What the alias is not
The alias is the value of the whole expression, not of the condition's truthiness. If the expression is a comparison, the alias is a boolean.
@if (items().length > 0; as hasItems) {
<!-- hasItems is always true here -->
}This is legal but useless, because inside the block the value can only be true. Aliasing pays off when the expression produces a value you want to use. It does not help when the expression is only a test.
Scope rules
The alias exists only in the block it is declared for. Three consequences follow:
- Content after the closing brace of the block cannot see the alias.
- A following
@elseor@else ifblock cannot see it. This is by design, since the alias is only defined when the condition was truthy. - Nested blocks inside the
@ifblock can see it, and so can bindings and event handlers inside that block.
You can alias in an @else if branch as well. Each alias belongs to its own branch.
@if (primary$ | async; as p) {
<p>Primary: {{ p.name }}</p>
} @else if (backup$ | async; as b) {
<p>Backup: {{ b.name }}</p>
} @else {
<p>No contact available.</p>
}Angular evaluates the branches in order and stops at the first truthy one. The second async pipe is only subscribed while the first branch's expression is falsy, so a subscription can start and stop as the first value changes. Keep this in mind when the second observable is expensive to start.
Aliases are also useful with nested access. The expression can be a long property path, and the alias gives it a short name:
@if (order()?.shipping?.address; as address) {
<p>{{ address.street }}, {{ address.city }}</p>
}The falsy-value trap
The alias only exists when the result is truthy, so every falsy value hides the block. In JavaScript the falsy values are false, 0, -0, 0n, '', null, undefined, and NaN. That makes aliasing risky for numbers and strings that can legitimately be zero or empty.
@if (unreadCount$ | async; as count) {
<span class="badge">{{ count }} unread</span>
}When unreadCount$ emits 0, nothing renders. That may be what you want, but if you wanted to show "0 unread", the block is silently skipped and no error warns you.
You have three options:
- Accept the behavior when "zero" and "nothing to show" mean the same thing.
- Test explicitly and keep the value in a separate step. For example, compare against
nullin the condition and read the value from a different binding. - Use
@let, which declares a template variable regardless of truthiness. It is available in current Angular versions, and it is covered in Angular's template syntax reference. Check which version your project uses before relying on it.
Alias or not: a decision guide
| Situation | Use the alias? | Reason | Column |
|---|---|---|---|
| `observable$ \ | async` used more than once in the block | Yes | One subscription, and the value is reused |
| Signal that may be `null`, and you read its properties | Yes | Narrows the type for the compiler | |
| Long property path read several times | Yes | Evaluates once and gives a short name | |
| Condition is a pure test such as `count() > 3` | No | The alias would always be `true` | |
| Value may legitimately be `0` or `''` | Usually no | The block would be hidden |
Common errors
- Writing
aswithout a semicolon.@if (user() as u)fails to compile. Write@if (user(); as u). - Using the alias in
@else. The name is not defined there. The compiler reports an unknown property on the component, because it looks the name up on the component class instead. - Reusing a component property's name. If the component has a
userfield and you aliasas user, the alias shadows the field inside the block. Choose distinct names to avoid confusion. - Piping before the semicolon and forgetting
AsyncPipe. In a standalone component,AsyncPipemust be inimports. The@ifblock itself needs no import.
Exercise
A template contains @if (cart$ | async) { <p>{{ (cart$ | async)?.items.length }} items</p> }. How many times does it subscribe to cart$, and how do you rewrite it to subscribe once and avoid the optional chain?
Show answer
It subscribes twice, once in the condition and once in the interpolation. Rewrite it as @if (cart$ | async; as cart) { <p>{{ cart.items.length }} items</p> }. The alias holds the emitted value, so there is one subscription, and inside the block cart is narrowed to a non-null type.
Exercise
A component has total = signal(0). The template is @if (total(); as t) { <p>Total: {{ t }}</p> } @else { <p>No total yet.</p> }. What renders when total is 0, and why might that be a bug?
Show answer
The @else block renders ("No total yet."), because 0 is falsy. If zero is a valid total that you want to display, this is a bug. Use a condition that tests for the missing case explicitly, such as a signal that holds number | null with a !== null check, or use @let to hold the value without a truthiness test.