为了创建动态列表,使用@ContentChild 指令访问投影内容。因此,当它们被投影时,应该使用“CONTEXT”作为 HOST || 调用它们的父组件。
应用程序动态列表 -> .ts 文件
@Input()
items: Array<any>;
@ContentChild('listItem', {static: false})
dynamicListTemplate: TemplateRef<any>;
应用动态列表 -> .html 文件
<ng-container *ngFor="let item of items;">
<ng-container
[ngTemplateOutlet]="listItem"
[ngTemplateOutletContext]="{ item: item}">
</ng-container>
</<ng-container
因此,当内容从父组件投影出来并且项目作为@Input 传递时。迭代每个项目并在项目键中传递项目对象,在这种情况下这将是一个对象,并且将使用 ng-template 中的 let-item 访问该项目。
注意:确保@ContentChild('listItem'...) 名称应与父组件标签中定义的#listItem 匹配。因此,相同的模板引用将在[ngTemplateOutlet]="listItem"中传递,以告诉 Angular 动态渲染哪个模板,因为多个模板可以存在于主机或子组件中。
<app-dynamic-list [items]="items">
// ContentChild Projected inside `app-dynamic-list` component
<ng-template #listItem let-item>
{{ item.id }} - {{ item.names.en }} ({{ item.names.np }})
</ng-template>
</app-dynamic-list>