In Angular, the ComponentResolver
has been deprecated and replaced with the ComponentFactoryResolver
as of Angular version 9. The ComponentFactoryResolver
provides a way to dynamically load and create components at runtime without relying on the deprecated ComponentResolver
. Here's how you can implement dynamic component loading using the ComponentFactoryResolver
.
- Import required dependencies: First, import the necessary modules and classes in your component where you want to dynamically load other components.
typescriptimport { Component, ComponentFactoryResolver, ViewChild, ViewContainerRef } from '@angular/core';
- Obtain a reference to the
ViewContainerRef
: To dynamically load components, you need access to aViewContainerRef
. This is the anchor point where you want to insert the dynamically created component. You can get theViewContainerRef
by using the@ViewChild
decorator.
typescript@Component({
selector: 'app-dynamic-loader',
template: '<ng-template #dynamicComponentContainer></ng-template>'
})
export class DynamicLoaderComponent {
@ViewChild('dynamicComponentContainer', { read: ViewContainerRef }) dynamicComponentContainer: ViewContainerRef;
}
- Load the component dynamically:
Now, you can use the
ComponentFactoryResolver
to dynamically load a component into theViewContainerRef
.
typescriptexport class DynamicLoaderComponent {
constructor(private componentFactoryResolver: ComponentFactoryResolver) {}
loadComponent(componentType: any) {
// Clear any existing components in the container
this.dynamicComponentContainer.clear();
// Get the component factory for the specified component type
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(componentType);
// Create and attach the component to the view container
const componentRef = this.dynamicComponentContainer.createComponent(componentFactory);
// Access the instance of the dynamically created component (optional)
const componentInstance = componentRef.instance;
// You can interact with the dynamically loaded component using its instance here
// For example, you can set input properties, call methods, etc.
}
}
Now, you can call the loadComponent
method with the component type you want to dynamically load.
typescript@Component({
selector: 'app-parent',
template: `
<button (click)="loadDynamicComponent()">Load Dynamic Component</button>
<app-dynamic-loader #dynamicLoader></app-dynamic-loader>
`
})
export class ParentComponent {
@ViewChild('dynamicLoader') dynamicLoader: DynamicLoaderComponent;
loadDynamicComponent() {
// Pass the component type you want to load dynamically
const componentType = YourDynamicComponent; // Replace with your actual component type
this.dynamicLoader.loadComponent(componentType);
}
}
With these steps, you can dynamically load and create components at runtime without using the deprecated ComponentResolver
. The ComponentFactoryResolver
is the recommended approach for dynamic component loading in Angular.