简体   繁体   中英

Add dynamic Components to ViewChildren

Currently, I can dynamically load a single component and display it in a ViewChild like this:

@Component({
   selector: '...',
   template: '<ng-container #viewRef></ng-container>'
})
export class SomeComponent {
@ViewChild('viewRef', {read: ViewContainerRef}) public viewRef;

  constructor(private compiler: Compiler) {}

  ngAfterViewInit() {
    this.compiler.compileModuleAndAllComponentsAsync(SomeModule).then((factory) =>  {
      this.componentRef = this.placeholder.createComponent(factory);
    });
  }
}

Now I would like to load multiple Components and display them dynamically in a list. ViewChildren should be the solution to this. The problem is, ViewChildren does not allow to add new elements or create them similar to createComponent on ViewChild .

How can I create dynamic components and add them to ViewChildren ?

You can use ViewChildren to get the QueryList of elements or directives from the view DOM. Any time a child element is added, removed, or moved, the query list will be updated, and the changes observable of the query list will emit a new value. That means that you can create a subscription on your viewRefs.changes event and load components dynamically using ComponentFactoryResolver . See the example below:

export class SomeComponent {
    @ViewChildren('viewRef', {read: ViewContainerRef})
    public viewRefs: QueryList<ViewContainerRef>;

    constructor(private componentFactoryResolver: ComponentFactoryResolver) {
    }

    ngAfterViewInit() {
        this.viewRefs.changes.subscribe((list: QueryList<ViewContainerRef>) => {
            list.forEach((viewRef: ViewContainerRef, index: number) => {
                const componentFactory: ComponentFactory<any> = this.componentFactoryResolver.resolveComponentFactory(OtherComponent);
                viewRef.createComponent(componentFactory, index);
            });
        });
    }
}

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