单击按钮时,我必须“生成”一个新组件,默认情况下,我想在加载后以及在浏览其他产品之后在页面上显示最后添加的产品。
检索所有产品时,在complete
函数上,我将调用createComponent()
方法并提供最后一个ID。
// global variables
@ViewChild('productDetails', {read: ViewContainerRef}) entry: ViewContainerRef;
componentRef: any;
// create child component method
createComponent(id: number) {
if (this.entry) {
this.entry.clear();
const factory = this.resolver.resolveComponentFactory(ProductDetailsComponent);
this.componentRef = this.entry.createComponent(factory);
this.componentRef.instance.id = this.id = id;
}
}
// Get list and generate component
ngOnInit() {
this.list$ = this.listService.getList().subscribe(
(response: IProducts[]) => {
response.map((item, index) => {
if (!this.id) {
this.id = +item.Id;
}
if (!item.IsExpired) {
item.style = 'card-disabled';
} else {
item.style = this.colors[index];
}
this.list.push(item);
});
},
reason => console.error(reason),
() => this.createComponent(this.id)
);
}
但是控制台第一次告诉我TypeError: Cannot read property 'clear' of undefined
。但是,在其他产品上单击其他按钮后,组件将正确显示。
答案 0 :(得分:0)
您的主要组件中是否有productDetails的实例?
您需要在template / html中添加productDetails 在html模板中添加div元素:
<div #productDetails></div>
答案 1 :(得分:0)
根据您对我的评论的回复:尝试将代码从ngOnInit移至ngAfterViewInit,我认为ViewContainerRef应该准备就绪
答案 2 :(得分:0)