Introducing let syntax in Angular

1 분 소요

Angular 18.1 introduces the @let syntax, which provides a formal way to declare and reuse variables directly within templates. This feature addresses the long-standing friction of using workarounds for local variable assignment.

1. The Previous Approach (Before)

To store expression results in a template, developers often relied on the as syntax within *ngIf or *ngFor.

 
<div *ngIf="user$ | async as user">
  {{ user.name }}
</div>


This required unnecessary DOM elements and could cause issues if the value was falsy, preventing the content from rendering at all.

2. The @let Syntax (After)

With the new @let syntax, you can declare variables independently of structural directives.

import { Component } from '@angular/core';
import { AsyncPipe } from '@angular/common';
import { of } from 'rxjs';

@Component({
  selector: 'app-let-example',
  standalone: true,
  imports: [AsyncPipe],
  template: `
    @let user = user$ | async;
    @let isAdmin = user?.role === 'admin';

    @if (user) {
      <section>
        <h1>Welcome,  {{ user.name }} </h1>
        <p>Role:  {{ isAdmin ? 'Administrator' : 'User' }} </p>
        
        @let statusText = user.active ? 'Online' : 'Offline';
        <span>Status:  {{ statusText }} </span>
      </section>
    }
  `
})
export class LetExampleComponent {
  user$ = of({ name: 'Adam Kim', role: 'admin', active: true });
}

3. Key Takeaways

  • Reactive: While variables are read-only, they are automatically recomputed during change detection (e.g., when an async pipe emits).
  • Scoped: Access is restricted to the current view and its children; it does not hoist out of blocks.
  • Control Flow Ready: It works seamlessly with the new @if and @for syntax.

Refernece

introducing-let-in-angular variables

한국어(Korean) Page

태그:

카테고리:

업데이트:

댓글남기기