【发布时间】:2017-03-18 01:07:38
【问题描述】:
我正在尝试在 Angular2 中构建一个列表组件,该组件从组件的用户那里获取项目字段的项目、列和模板。所以我正在尝试使用ngTemplateOutlet 和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" }
];
这是一个 plunker 在根据 Günters 评论调整代码后重现该问题: https://plnkr.co/edit/jB6ueHyEKOjpFZjxpWEv?p=preview
【问题讨论】:
-
您是否尝试将
TemplateRef作为字符串传递?一种方法plnkr.co/edit/3yM25cUVeP4fK0cxhpXp?p=preview -
另一种方法是使用
ContentChildrenplnkr.co/edit/2Ohj12Gax6UaK6LJ5dwD?p=preview -
@yurzui 有趣。你的版本是如何工作的,而不是我的?不,列需要是对象列表,因为我通过它传递附加信息,如标题以及它当前是否应该显示。看来您的 plunker 和我的唯一区别是您将列作为字符串列表传递。
-
ngTemplateOutlet参数应该是TemplateRef实例,但在你的情况下它是string -
在您的模板中
<template #model>model将是 TemplateRef 实例。如果您想在组件中使用model作为 TemplateRef,那么您应该查看ViewChild(ViewChildren) stackoverflow.com/questions/39908967/… 另请参阅 angular.io/docs/ts/latest/guide/template-syntax.html#!#ref-vars
标签: angular