Menu
×
   ❮     
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL MONGODB ASP AI R GO KOTLIN SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING BASH RUST

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 use u 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>

Run Example ยป

Example explained

  • *ngIf="user as u": When user is truthy, create a local alias u that holds the value of user.
  • Alias use: Inside the block, use u.name instead of repeating user.name.
  • else empty: When user is falsy, render the template referenced by #empty.
  • toggle(): The button switches user between null and an object to demonstrate both paths.


×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2025 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.