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 useuinside. - Makes templates cleaner by not repeating expressions.
When to use alias with as
- When the same expression is referenced several times.
- When using an
elsetemplate 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": Whenuseris truthy, create a local aliasuthat holds the value ofuser.- Alias use: Inside the block, use
u.nameinstead of repeatinguser.name. else empty: Whenuseris falsy, render the template referenced by#empty.toggle(): The button switchesuserbetweennulland an object to demonstrate both paths.