我正在尝试在Angular2中构建一个列表组件,该组件使用了来自组件用户的项目字段的项目,列和模板。所以我试图使用ngTemplateOutlet
和ngOutletContext
(我读过的是实验性的)。但我无法让它工作。无法让ngTemplateOutlet工作
下面是一个简单的组件来证明什么,我试图做的:
<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评论: https://plnkr.co/edit/jB6ueHyEKOjpFZjxpWEv?p=preview
你是不是想通过'TemplateRef'为字符串?一种方法https://plnkr.co/edit/3yM25cUVeP4fK0cxhpXp?p=preview – yurzui
另一种方式是使用'ContentChildren' https://plnkr.co/edit/2Ohj12Gax6UaK6LJ5dwD?p=preview – yurzui
@yurzui有趣的。你的版本如何工作,而不是我的?不,列需要是一个对象列表,因为我像头一样传递附加信息,如果它现在应该显示或不显示。看起来你和我的朋友之间唯一的区别就是你将字段作为字符串列表传递。 – Hampus