Angular Templates: Alias with as in *ngIf
Create a local alias from a truthy value using as
to avoid repeating expressions.
What is alias with as
in *ngIf
?
- Create a local alias for the truthy value of the condition.
- Example:
*ngIf="user as u"
then useu
inside. - Makes templates cleaner by not repeating expressions.
When to use alias with as
- When the same expression is referenced several times.
- When using an
else
template that also needs the value. - To improve readability and reduce duplication.
Examples live under Conditional Rendering (*ngIf
with as
and else
).
Example
import { bootstrapApplication } from '@angular/platform-browser';
import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
@Component({
selector: 'app-root',
standalone: true,
imports: [CommonModule],
template: `
<button (click)="toggle()">Toggle user</button>
<p *ngIf="user as u; else empty">Hello {{ u.name }}!</p>
<ng-template #empty>No user</ng-template>
`
})
export class App {
user: { name: string } | null = { name: 'Ada' };
toggle() { this.user = this.user ? null : { name: 'Ada' }; }
}
bootstrapApplication(App);
<app-root></app-root>
Example explained
*ngIf="user as u"
: Whenuser
is truthy, create a local aliasu
that holds the value ofuser
.- Alias use: Inside the block, use
u.name
instead of repeatinguser.name
. else empty
: Whenuser
is falsy, render the template referenced by#empty
.toggle()
: The button switchesuser
betweennull
and an object to demonstrate both paths.