编辑:我发现[ngTemplateOutlet]
似乎更合适。讨论在Can't get ngTemplateOutlet to work
原始问题:
我已经构建了一个表组件,我将在多个不同的视图中使用它来呈现不同的数据。该数据及其表示应由表组件的使用者控制。
我尝试使用<ng-content>
传递一个“渲染器”,它知道如何检索该数据以及如何呈现它。您可能理解,这是非法使用。
以下是我尝试使用<ng-content>
的简化方法。
这是表组件模板:
<table>
<thead>
<tr>
<th *ngFor="let column in columns">{{column.heading}}</th>
<tr>
</thead>
<tbody>
<tr *ngFor="let item of items>
<td *ngFor="let column of columns>
<ng-content select="{{column.template}}"></ng-content>
</td>
</tr>
</tbody>
</table>
以下是表组件的用法:
<my-table-component [items]="cars" [columns]="carColumns">
<div class="model">{{item.model}}</div>
<div class="color">{{item.color}}</div>
<div class="gearbox>{{item.gearbox}}</div>
</my-table-component>
以下是示例数据:
cars = [
{ model: "volvo", color: "blue", gearbox: "manual" },
{ model: "volvo", color: "yellow", gearbox: "manual" },
{ model: "ford", color: "blue", gearbox: "automatic" },
{ model: "mercedes", color: "silver", gearbox: "automatic" }
];
carColumns = [
{ heading: "Model", template: ".model" },
{ heading: "Color", template: ".color" },
{ heading: "Gear Box", template: ".gearbox" }
];
通过这个我希望你明白我想要做什么。显而易见的问题似乎是<ng-content>
在“循环”中不起作用,并且它不接受动态“选择”。此外,item
当然不能选择表组件使用者。
很可能还有其他“不要”。
由于我是棱角分明2的新手,我希望我误会了某些事情,或者说我使用了错误的工具。有什么想法吗?
答案 0 :(得分:0)
[ngTemplateOutlet]
和[ngOutletContext]
更适合此用例。以下是相同用例的工作示例:
Can't get ngTemplateOutlet to work