Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

In the ng-bootstrap modal documentation there are uses of some kind of let-* attribute that seemed to be used to link a function or event for later use. If you look at the (click) events and the let-c / let-d attributes at the top of the examples, you can get a feel for what it does. This appears to be a feature of Angular and has nothing to do with ng-bootstrap.

But what is this called? What does it do? Where are the Angular docs for this feature?

Here's an example of what I'm referring to. See the very first line.

<ng-template #content let-c="close" let-d="dismiss">
  <div class="modal-header">
    <h4 class="modal-title" id="modal-basic-title">Profile update</h4>
    <button type="button" class="close" aria-label="Close" (click)="d('Cross click')">
      <span aria-hidden="true">&times;</span>
    </button>
  </div>
  <div class="modal-body">
    <!-- content here omitted -->
  </div>
  <div class="modal-footer">
    <button type="button" class="btn btn-outline-dark" (click)="c('Save click')">Save</button>
  </div>
</ng-template>

I've Googled this to no avail; the only results I get are about the let keyword when using ngFor, which is obviously not related.

like image 999
pbarranis Avatar asked Jul 18 '18 23:07

pbarranis


1 Answers

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.

like image 76
Reactgular Avatar answered Oct 18 '22 03:10

Reactgular