How do I pass an ngFor variable to the ng-content template.
Example, the containing-component:
<ul>
<li *ngFor="let item of itemsArray">
<ng-content></ng-content>
</li>
</ul>
The nested content-component:
<div>
<span *ngIf="item.type_one"></span>
<span *ngIf="item.type_two"></span>
</div>
Example, both:
<containing-component>
<content-component>
</content-component>
</containing-component>
You can not use ng-content
as dynamic template. Use ng-template
instead
<ul>
<li *ngFor="let item of itemsArray">
<ng-container *ngTemplateOutlet="itemTemplate; context: { $implicit: item }">
</ng-container>
</li>
</ul>
export class ContainingComponent {
...
@ContentChild(TemplateRef, {static: true})
@Input() itemTemplate: TemplateRef<any>;
}
So you can reference dynamic template into containing-component
. In this case, you can wrap ng-template over content-component
<containing-component [itemTemplate]="itemTmpl">
</containing-component>
<ng-template #itemTmpl let-data>
<content-component
[item]="data">
</content-component>
</ng-template>
Or use ng-template directly
:
<containing-component
[itemTemplate]="itemTmpl"
[itemArray]="items">
</containing-component>
<ng-template #itemTmpl let-data>
<div>
<span *ngIf="data.type_one"></span>
<span *ngIf="data.type_two"></span>
</div>
</ng-template>
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