How to use @let in Angular (with examples)
Angular recently buzzed the community by introducing the new control-flow syntax.
But they didn't stop there.
They're also introducing the new @let
syntax.
It's as simple as this.
@let name = 'You';
<h1>{{ name }} </h1>
The @let
name is obviously based off of the JavaScript let declaration.
It let's you declare variables inside your components template code.
However, a key difference between @let
and JavaScript's let is that @let
cannot be reassigned after declaration.
In other words, this doesn't work.
@let name = 'You';
@let name = 'Me';
<h1>{{ name }} </h1>
So, before we get started, make sure you've installed the latest version of the Angular CLI and upgraded your project to the latest stable release.
And then we'll explore some common scenarios where you might use Angular's @let
syntax in an enterprise Angular app.
1. Async Data Handling (API Calls)
When subscribing to asynchronous data (e.g., via HTTP calls or WebSockets), @let
allows you to easily handle the loading state and conditional display of data.
@let products = products$ | async;
@if (products) {
// render
}
@else {
<p>Loading...</p>
}
2. Conditional UI Rendering
You can use it to show or hide sections of the UI based on the result of an observable or promise.
@let isLoggedIn = authService.isLoggedIn$ | async;
@if (isLoggedIn) {
<app-dashboard/>
}
3. Reduce Repeated Async Pipe Usage
I absolutely love this use-case 🤩 🤩 🤩
If you need to reuse the same observable in different parts of a template, @let
eliminates multiple async
pipe invocations, reducing redundancy and boosting performance.
@let user = user$ | async;
<span>{{ user.name }}</span>
<span>{{ user.email }}</span>
<span>{{ user.phoneNumber }}</span>
These scenarios show how @let
can simplify working with asynchronous data and improve the readability of templates in enterprise Angular applications.
``typescript @let blogPostFinished = true;
I have no doubt that this new `@let` feature will greatly enhance the development experience for Angular devs.
So, enjoy Angular!
Till next time,
![signature](signature.png "signature")