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);
});
});
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With