DEV Community

Nhan Nguyen
Nhan Nguyen

Posted on

Angular's next feature @let syntax

We can check the pull request here: https://github.com/angular/angular/pull/55848

Let's discuss the various use cases and advantages of the new @let syntax.

The @let syntax allows us to declare and use local variables within our Angular templates.

@let user = user$ | async;
@let greeting = user ? 'Hello, ' + user.name : 'Loading...';

<h1>{{ greeting }}</h1>
Enter fullscreen mode Exit fullscreen mode

In the above example, user$ is an observable that emits user data. The @let syntax simplifies handling asynchronous data and conditional rendering.

🚀 Use Cases:

➖ Using the async pipe directly in multiple places can lead to multiple subscriptions, which is inefficient and can cause performance issues:

<div>{{ total$ | async }}</div>
<div>{{ total$ | async }}</div>
Enter fullscreen mode Exit fullscreen mode

The solution is to use the @let syntax to declare a variable for the observable value. This approach ensures a single subscription.

@let total = total$ | async;

<div>{{ total }}</div>
<div>{{ total }}</div>
Enter fullscreen mode Exit fullscreen mode

➖ One of the most annoying issues with signals is their lack of type narrowing ability within the template. We can use the @let feature to resolve this problem:

@let txType = tx().type;

@switch(txType) {
  @case('a') {}
  @case('b') {}
}

@let address = person()?.address();

@if (address) {
 <app-address [address]="address">
}
Enter fullscreen mode Exit fullscreen mode

➖ The @let syntax particularly useful within @for loops. We can create intermediate properties directly in the template, enhancing readability and reducing the need for additional component logic:

@for (user of users(); track user.id) {
  @let address = user.address;

  <div>
    <h3>User: {{ user.name }}</h3>
    <div>
      <p>Street: {{ address.street }}</p>
      <p>City: {{ address.city }}</p>
      <p>Zipcode: {{ address.zipcode }}</p>
    </div>
    @for (order of user.orders) {
      <div>
        <h4>Order: {{ order.id }}</h4>
        <p>Product: {{ order.productName }}</p>
        <p>Quantity: {{ order.quantity }}</p>
      </div>
    }
  </div>
}
Enter fullscreen mode Exit fullscreen mode

➖ Using an expensive pipe multiple times in a template often necessitates creating a property in the component to store the transformed data. With the @let syntax, we can declare and reuse a transformed variable once, reducing the computational load and keeping our template clean:

@let someResult = someData | somePipe;

<p>{{ someResult }}</p>
<p>{{ someResult }}</p>
Enter fullscreen mode Exit fullscreen mode

Conclusion

This new feature enhances the development experience for Angular developers by addressing common challenges such as managing falsy values, avoiding multiple subscriptions, and reducing repetitive code.


I hope you found it helpful. Thanks for reading. 🙏

Let's get connected! You can find me on:

Top comments (0)