Intro
@let
block that allows you to define a variable in a template and reuse it in many places.
@let tasks = tasks$ | async;
} @else if(tasks.length > 0) {
@for(let task of tasks) {
@let
and Type Narrowing
The @let
block can be used to narrow the type of a variable in a template.
It is especially useful when you have a signals based application.
| { status : " LOADED " ; data : string [] }
| { status : " ERROR " ; error : string };
export class AppComponent {
const state = signal ({ name: " PRISTINE " });
@if(state.status === "LOADING") {
} @else if(state.status === "LOADED") {
<!-- state has type `{ status: "LOADED"; data: string[] }` -->
@for(let task of state.data) {
<!-- state has type `{ status: "ERROR"; error: string }` -->
To do the same with *ngIf
, you would have to repeat the type check in each *ngIf
block
export class AppComponent {
state = signal ({ name: " LOADING " });
isLoaded ( state : ComponentState ) : { status : " LOADED " ; data : string [] } | false {
return state . status === " LOADED " ? state : false ;
< ng-container *ngIf = " isLoaded(state()); as loadedState " >
<!-- loadedState has type `{ status: "LOADED"; data: string[] }` -->
@for(let task of loadedState.data) {
Source