如何将ngFor变量传递给ng-content模板。
示例,包含组件:
<ul>
<li *ngFor="let item of itemsArray">
<ng-content></ng-content>
</li>
</ul>
嵌套的内容组件:
<div>
<span *ngIf="item.type_one"></span>
<span *ngIf="item.type_two"></span>
</div>
均为示例
<containing-component>
<content-component>
</content-component>
</containing-component>
答案 0 :(得分:2)
您不能将ng-content
用作动态模板。请改用ng-template
<ul>
<li *ngFor="let item of itemsArray">
<ng-container *ngTemplateOutlet="itemTemplate; context: { $implicit: item }">
</ng-container>
</li>
</ul>
export class ContainingComponent {
...
@ContentChild(TemplateRef)
@Input() itemTemplate: TemplateRef<any>;
}
因此您可以将动态模板引用到containing-component
中。在这种情况下,您可以将ng-template包装在content-component
<containing-component [itemTemplate]="itemTmpl">
</containing-component>
<ng-template #itemTmpl let-data>
<content-component
[item]="data">
</content-component>
</ng-template>
或使用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>