How to add dynamic components to ViewChildren?

3.6K    Asked by Manishsharma in Python , Asked on Jan 14, 2020
Answered by Arun Singh

We 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 we can create a subscription on our viewRefs.changes event and load components dynamically using ComponentFactoryResolver.


See the example below:

export class SomeComponent {

    @ViewChildren('viewRef', {read: ViewContainerRef})

    public viewRefs: QueryList;

    constructor(private componentFactoryResolver: ComponentFactoryResolver) {

    }

    ngAfterViewInit() {

        this.viewRefs.changes.subscribe((list: QueryList) => {

            list.forEach((viewRef: ViewContainerRef, index: number) => {

                const componentFactory: ComponentFactory = this.componentFactoryResolver.resolveComponentFactory(OtherComponent);

                viewRef.createComponent(componentFactory, index);

            });

        });

    }

}



Your Answer

Interviews

Parent Categories