Мне нужно «создать» новый компонент по нажатию кнопки, по умолчанию я хочу показать последний добавленный продукт на странице после загрузки и после навигации по другим продуктам.
Когда я получу весь продукт, в функции complete
я вызову метод createComponent()
и предоставлю последний идентификатор.
// 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
.Но после других нажатий на другой продукт компонент отображается правильно.