What is let- syntax in a template?
In Angular, let syntax in a template is used to declare local variables inside structural directives (*ngFor, *ngIf, ng-template), to work with data or state at the template level.
Main points
- In
*ngFor- creates a variable for the current iteration item:
html
<li *ngFor="let item of items">{{ item.name }}</li>itemis a local variable representing the current element of theitemsarray.
- Additional local variables in
*ngFor:
html
<li *ngFor="let item of items; let i = index; let isFirst = first">
{{ i }} - {{ item.name }} (First: {{ isFirst }})
</li>iis the element's index,isFirstis true for the first element.
- In
ng-template- allows passing values from the context:
html
<ng-template #tpl let-name="userName">
<p>{{ name }}</p>
</ng-template>let-name="userName"declares a local variablenamethat takes its value from theuserNamecontext.
In other words, let in a template is a way to create local variables for convenient access to data and context inside directives and templates, without changing the component class.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.