What is the "let-" attribute in Angular 6? What is the "let-" attribute in Angular 6? angular angular

What is the "let-" attribute in Angular 6?


The let-* attribute is a feature of the ng-template to inject a variable into the template by sourcing the variable's value from the context.

<ng-template #example let-title="fooBar">     <span>{{title}}</span></ng-template>

In the above example the template variable title exists because there is let-title and it's value will be equal to the property fooBar from the context object.

<ng-container *ngTemplateOutlet="example; context: {fooBar:'This is the value'}"></ng-container>

The above inserts the template reference #example and passes it the context.

There are multiple ways to use a template but the let-* is the only way to inject template variables.

Reference for NgComponent:

https://angular.io/api/common/NgComponentOutlet

Reference to the let microsyntax:

https://angular.io/guide/structural-directives#microsyntax

A nice blog on the topic:

https://blog.angular-university.io/angular-ng-template-ng-container-ngtemplateoutlet/

It's difficult to find information about let because it's part of the Angular microsyntax parser. Which is used by both templates and *ngFor.

Maybe you've seen this before in Angular.

<div ngFor let-item [ngForOf]="items" let-i="index">....</div>

The above is the same as writing.

<div *ngFor="let item of items; let i=index">....</div>

So there are two ways to write a let-* assignment in Angular. This is what they call the microsyntax parser. You can actually write your own directives that use this special syntax, but you have to look at the source of Angular to figure it out.


Third party angular libraries will sometimes introduce their own support for directives. Here's one example from primeng:

<ng-template pTemplate="body" let-item let-columns="columns" let-rowIndex="rowIndex">

This will make sense after reading the primeng docs.