What is the “let-” attribute in Angular 6?

允我心安 提交于 2020-05-25 17:04:53

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/51412174/what-is-the-let-attribute-in-angular-6

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!