Reputation: 182
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.
I'm rather new with angular 2 so any help would be appreciated.
Upvotes: 0
Views: 4332
Reputation: 56
Change the loadComponent function to this:
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.
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
import { ChangeDetectorRef, (...) } from '@angular/core';
constructor(
private cd: ChangeDetectorRef,
private componentFactoryResolver: ComponentFactoryResolver
) { }
ngAfterViewInit() {
this.loadComponent();
this.getAds();
this.cd.detectChanges();
}
Upvotes: 4