我正在尝试在 Angular2 中构建一个列表组件,该组件从组件的用户那里获取项目、列和项目字段的模板。所以我正在尝试使用ngTemplateOutlet
and ngOutletContext
(我读过的都是实验性的)。但我无法让它发挥作用。
这是一个简化的组件,用于演示我正在尝试执行的操作:
<div *ngFor="let item of items>
<span *ngFor="let column of columns>
<template [ngOutletContext]="{ item: item }"
[ngTemplateOutlet]="column.templateRef"></template>
</span>
</div>
下面是该组件的用法:
<my-component [items]="cars" [columns]="carColumns">
<template #model>{{item.model}}</template>
<template #color>{{item.color}}</template>
<template #gearbox>{{item.gearbox}}</template>
</my-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 = [
{ templateRef: "model" },
{ templateRef: "color" },
{ templateRef: "gearbox" }
];
这是一个根据 Günters 评论调整代码后重现问题的 plunker:https://plnkr.co/edit/jB6ueHyEKOjpFZjxpWEv?p=preview https://plnkr.co/edit/jB6ueHyEKOjpFZjxpWEv?p=preview