我正在尝试在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
作为字符串传递?一种方法是使用 https://plnkr.co/edit/3yM25cUVeP4fK0cxhpXp?p=preview - yurzuiContentChildren
https://plnkr.co/edit/2Ohj12Gax6UaK6LJ5dwD?p=preview - yurzuingTemplateOutlet
param should beTemplateRef
instance but in your case it'sstring
- yurzui<template #model>
中,model
将是一个TemplateRef实例。如果您想在组件中将model
用作TemplateRef,则应查看ViewChild(ViewChildren)https://dev59.com/VVkS5IYBdhLWcg3waWDD#39909203 还请参阅https://angular.io/docs/ts/latest/guide/template-syntax.html#!#ref-vars - yurzui