Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

typescript - Angular 2 bind transcluded content to loop variable

I'm trying to bind transcluded content to a variable inside of a component loop but I'm unable to do so.

I've looked at the PrimeNG's dropdowncomponent and they use the template tag along with let-car to bind to the car variable of the loop.

However when I try this I can't even get the content to transclude. What is the correct way of achieving this?

Attempts:

<!-- Obviously not gonna work -->
<comp>
  <span>{{option.name}}, {{option.type}}</span>
</comp>

<!-- Thought this would work but it doesn't, in odd scenarios I get the last element of the loop to transclude content and bind correctly. -->
<comp>
  <template let-option>
    <span>{{option.name}}, {{option.type}}</span>
  </template>
</comp>

In component:

<ul>
  <li *ngFor="let option of options">
    <ng-content></ng-content>
  </li>
</ul>

Simple plunkr of what I'm trying to achieve:

https://plnkr.co/edit/6SS03fuXmbvJB4nmf1AO?p=preview

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Update Angular 6

ngOutletContext was renamed to ngTemplateOutletContext template should be ng-template

See also https://github.com/angular/angular/blob/master/CHANGELOG.md#500-beta5-2017-08-29

Original

You can get the template reference and add it using for example ngTemplateOutlet or ngForTemplate to get the template content added to the DOM. With ngTemplateOutlet you can provide your own context that you then can access with template variables as you tried.

class CompComponent {
  context = {option: 'some option'};
  constructor(private templateRef:TemplateRef){}
}
<ng-template [ngTemplateOutlet]="templateRef" [ngOutletContext]="{$implicit: context}"></ng-template>

I think in newer versions this needs to be

<ng-template [ngTemplateOutlet]="templateRef" [ngTemplateOutletContext]="{$implicit: context}"></ng-template>

(but haven't yet verified)

See also


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...