Skip to main content

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

  1. In *ngFor - creates a variable for the current iteration item:
html
<li *ngFor="let item of items">{{ item.name }}</li>
  • item is a local variable representing the current element of the items array.
  1. Additional local variables in *ngFor:
html
<li *ngFor="let item of items; let i = index; let isFirst = first"> {{ i }} - {{ item.name }} (First: {{ isFirst }}) </li>
  • i is the element's index, isFirst is true for the first element.
  1. 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 variable name that takes its value from the userName context.

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 ready
Premium

A concise answer to help you respond confidently on this topic during an interview.