问题描述
我正在尝试在Angular2中构建一个列表组件,该组件从组件的用户那里获取项目,项目的列和字段的模板.所以我正在尝试使用ngTemplateOutlet
和ngOutletContext
(我读过的是实验性的).但是我无法使其正常工作.
I am trying to build a listing component in Angular2 that takes the items, the columns and the templates for the fields of the items from the user of the component. So I am trying to use ngTemplateOutlet
and ngOutletContext
(which I have read are experimental). But I cannot get it to work.
这里是一个简化的组件,用于演示我正在尝试做的事情:
Here is a simplified component to demonstrate what I am trying to do:
<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
Here is a plunker reproducing the issue after adapting the code according to Günters comment:https://plnkr.co/edit/jB6ueHyEKOjpFZjxpWEv?p=preview
推荐答案
这是您需要执行的操作:
This is how you need to do this:
@Component({
selector: 'my-component',
template: `
<div *ngFor="let item of items">
<span *ngFor="let column of columns">
<template [ngTemplateOutlet]="column.ref" [ngOutletContext]="{ item: item }"></template>
</span>
</div>`
})
export class MyComponent {
@Input() items: any[];
@Input() columns: any[];
}
@Component({
selector: 'my-app',
template: `
<div>
<my-component [items]="cars" [columns]="columns">
<template #model let-item="item">{{item?.model}}</template>
<template #color let-item="item">{{item?.color}}</template>
</my-component>
</div>`
})
export class App {
@ViewChild('model') model;
@ViewChild('color') color;
cars = [
{ model: "volvo", color: "blue" },
{ model: "saab", color: "yellow" },
{ model: "ford", color: "green" },
{ model: "vw", color: "orange" }
];
ngAfterContentInit() {
this.columns = [
{ ref: this.model },
{ ref: this.color ]
];
}
}
这篇关于无法让ngTemplateOutlet工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!