[英]How to show a list of dynamically added components in angular 2
Take the angular feature to dynamically add components. 利用角度特征动态添加零部件。
I need help to make it so we show the list of ads directly on the page rather than one after the other. 我需要帮助,因此我们直接在页面上显示广告列表,而不是一个接一个地显示。
I thought it would be as simple as adding *ngFor on the ng-template element but it seems more complicated than this. 我认为这就像在ng-template元素上添加* ngFor一样简单,但是似乎比这复杂。
I'm rather new with angular 2 so any help would be appreciated. 我对angular 2还是比较陌生,因此不胜感激。
Change the loadComponent function to this: 将loadComponent函数更改为此:
loadComponent() {
let viewContainerRef = this.adHost.viewContainerRef;
for (const ad of this.ads) {
let componentFactory = this.componentFactoryResolver.resolveComponentFactory(ad.component);
let componentRef = viewContainerRef.createComponent(componentFactory);
(<AdComponent>componentRef.instance).data = ad.data;
}
}
The viewContainer inserts the views one after the other. viewContainer一个接一个地插入视图。
EDIT: 编辑:
About the error thrown. 关于抛出的错误。 It's better with a piece of code.
最好用一段代码。 And here's a more thorough explanation of the problem: https://blog.angularindepth.com/everything-you-need-to-know-about-the-expressionchangedafterithasbeencheckederror-error-e3fd9ce7dbb4
这是对该问题的更详尽的解释: https : //blog.angularindepth.com/everything-you-need-to-know-about-the-expressionchangedafterithasbeencheckederror-error-e3fd9ce7dbb4
import { ChangeDetectorRef, (...) } from '@angular/core';
constructor(
private cd: ChangeDetectorRef,
private componentFactoryResolver: ComponentFactoryResolver
) { }
ngAfterViewInit() {
this.loadComponent();
this.getAds();
this.cd.detectChanges();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.