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 dropdown
component 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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With