gpt4 book ai didi

angular - 如何让实验性的 ngTemplateOutlet 工作?

转载 作者:太空狗 更新时间:2023-10-29 16:51:44 27 4
gpt4 key购买 nike

我正在尝试在 Angular2 中构建一个列表组件,它从组件的用户那里获取项目、列和项目字段的模板。所以我正在尝试使用 ngTemplateOutletngOutletContext(我读过的是实验性的)。但我无法让它工作。

这是一个简化的组件来演示我正在尝试做的事情:

<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

最佳答案

这是您需要执行此操作的方式:

@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 ]
];
}
}

Plunker

关于angular - 如何让实验性的 ngTemplateOutlet 工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40418598/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com