【发布时间】:2019-03-18 22:48:29
【问题描述】:
我创建了我的自定义结构指令,它应该为传递的项目数组中的每个元素呈现宿主元素:
@Directive({
selector: '[appItems]'
})
export class ItemsDirective implements OnInit, OnChanges {
@Input('appItemsOf')
items: any[];
constructor(private container: ViewContainerRef,
private template: TemplateRef<any>) {
}
ngOnInit(): void {
this.container.createEmbeddedView(this.template);
}
ngOnChanges(): void {
this.container.clear();
for (const item of this.items) {
if (item) {
this.container.createEmbeddedView(this.template, {
$implicit: item,
index: this.items.indexOf(item)
});
}
}
}
}
用法:
<div *appItems="let item of items">
Item: {{ item.name }}
</div>
不幸的是,打印出来了:
Item: 1
Item: 2
Item: 3
Item:
虽然项目数组看起来像这样,但正在创建和渲染最后一个元素:
items = [
{
name: '1'
},
{
name: '2'
},
{
name: '3'
}
]
我创建了一个 https://stackblitz.com/edit/angular-qwatckstackblitz 来显示这个问题。
为什么会这样,应该如何正确完成?
【问题讨论】: