Tuesday 13 August 2024

new @let block in Angular templates



<div>
@let userName = (userName$ | async) ?? 'Guest'; <h1>Welcome, {{ userName }}</h1> </div>


<table mat-table [dataSource]="dataSource">
@for (columnDef of columnDefs) {
@let property = columnDef.propertyName;
<ng-container [matColumnDef]="columnDef.name">
<th mat-header-cell *matHeaderCellDef>{{ columnDef.header }}</th>
<td mat-cell *matCellDef="let element">
@let cellValue = element[property];
<ng-container *ngIf="columnDef.cellType === 'link'; else plainCell">
<a [routerLink]="cellValue?.routerLink">{{ cellValue?.value }}</a>
</ng-container>
<ng-template #plainCell>{{ cellValue }}</ng-template>
</td>
</ng-container>
}
</table>



<div>
@let firstName = user?.firstName;
@let lastName = user?.lastName;
@let fullName = `${firstName} ${lastName}`;
<p>{{ fullName }}</p>
@if (user?.address) {
@let street = user.address.street;
@let city = user.address.city;
<p>{{ street }}, {{ city }}</p>
}
</div>


Conclusion 

 @let syntax in Angular, combined with the new control flow features like @if and @for, offers a significant improvement for template variable declarations and control flow management. While some may argue for the continued use of signals for state management, the @let syntax provides an elegant solution for handling local variables within templates. By addressing common challenges such as managing falsy values, avoiding multiple subscriptions, and reducing repetitive code, this new feature is poised to enhance the development experience for Angular developers.