Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add dynamic Components to ViewChildren

Tags:

angular

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?

like image 346
Thomas Schneiter Avatar asked Feb 18 '19 08:02

Thomas Schneiter


1 Answers

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);
            });
        });
    }
}
like image 121
dim0_0n Avatar answered Nov 07 '22 05:11

dim0_0n