Angular 18.1 brought a new feature to our Angular templates: the ability to create local variables. Just like the new control-flow blocks @if
, @for
, and @switch
, the new syntax uses the @
character with a new keyword: @let
.
Here is an example:
The above code displays 21 as the value of the Angular expression. Why is this helpful? In many cases, we deal with complex nested objects that translate into long, verbose expressions:
With @let
, we can make things shorter:
Another major use case is when using the async pipe. I covered several tricks on how to use the async pipe in the past, even introducing ngrxLet
as an alternative, and all of these tricks can now be replaced with @let
.
Here is the initial problem with async when dealing with data from an Observable that we need in several places:
The above syntax is not only horrible, but it also multiplies subscriptions to the source Observable, which is even worse. The common workaround consisted of using a structural directive because such directives allow using local variables as follows:
That’s more readable but still not ideal. Here is what we can do with @let
now:
That’s a lot better. If the multiple ?
drive you crazy, you can do this instead:
@let
variables are read-only and cannot be reassigned. They behave like the const
keyword in Javascript. The scope is also to the nearest block (which means view, in the case of Angular templates), so in my above example, addr
is only available within the @if
block, invisible outside of it.
You can play with my examples on Stackblitz here.