Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 848
Chrillewoodz Avatar asked Dec 20 '16 10:12

Chrillewoodz


1 Answers

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

  • How to repeat a piece of HTML multiple times without ngFor and without another @Component
  • Angular2 child component as data
like image 63
Günter Zöchbauer Avatar answered Oct 17 '22 22:10

Günter Zöchbauer