简体   繁体   中英

How to show a list of dynamically added components in angular 2

Take the angular feature to dynamically add components.

Documentation

Demo

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.

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(); 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM