Angular

@let in Angular


Probably many Angular developers have wished for the way to declare and define variables inside the template. To address this, Angular 18 introduces the @let directive.  The @let directive allows developers to use easily and render within the template. It can be further used to store the value and then use it later for logics. The most common use for the @let directive is to declare the variable for an alias.

How to use @let variables?

1. For Basic Calculations

<div>   @for (flight of flightData; track flight.id) {       @let totalAmount = previousFlightRate + flight.rate;        <h1>Total charged amount: {{ totalAmount }}</h1>   }</div> 

2. With Signals

<div>    @let userName = loggedInUser()?.fullName ?? 'Guest';   <h1>Hi, {{ userName }}!</h1></div>

 

3. With function’s return value

<div>   @for (flight of flightData; track flight.id) {       @let days = calculateJourneyDays(flight.inBoundDate, flight.outBoundDate);        <h1>Total Journey Days : {{ days }} !</h1>   }</div>

 

4. With Async Pipe

<div>   @let userData = (loggedInUser$ | async) ?? { name: 'Guest' };    <h1>{{ userData.name }}</h1></div>

 

5. With repitative Logic 

@let contentCondition = loggedInUser.active &&!loggedInUser.isDeleted && accountType;@if (contentCondition) {   <div>Content1</div>}<div>Content2</div>@if (contentCondition) {   <small>Content1</small>} 

Advanced usage of @let

1. Improves code readability.

2. Reduces the load on computational blocks by calculating values only when they are in use.

3. Allows for the reuse of variables within the scope.

Scope and Limitations

When we define a variable using @let, it is scoped to the current view only and cannot be accessed in child or parent components. For example,

@let outerScope = value;@if (condition) { @let innerScope = value;}<!-- Valid -->{{outerScope}}<!-- Error: Not accessible outside the defined scope -->{{innerScope}} 

Improvements in Real-World Projects

The @let directive has been introduced alongside other directives such as @if and @for. The @let directive provides a significant way to handle complex logic and expressions directly within the template. Since TypeScript developers are already familiar with concepts like let, const and var, they can easily adapt to this feature, resulting in cleaner and more dynamic code.

This enhancement aims to improve the developer experience by avoiding multiple subscriptions, handling falsy values more effectively and reducing repetitive or complex structures in the code.

 

Ready to transform your business with our technology solutions? Contact Us today to Leverage Our Angular Expertise. 

0

Angular

Related Center Of Excellence