I am currently loading angular components dynamically in my application using following code.
export class WizardTabContentContainer { @ViewChild('target', { read: ViewContainerRef }) target: any; @Input() TabContent: any | string; cmpRef: ComponentRef<any>; private isViewInitialized: boolean = false; constructor(private componentFactoryResolver: ComponentFactoryResolver, private compiler: Compiler) { } updateComponent() { if (!this.isViewInitialized) { return; } if (this.cmpRef) { this.cmpRef.destroy(); } let factory = this.componentFactoryResolver.resolveComponentFactory(this.TabContent); this.cmpRef = this.target.createComponent(factory); } }
Here resolveComponentFactory function accepts component type. My question is, Is there any way I can load component using component name string e.g I have component defined as
export class MyComponent{ }
How can I add above component using component name string "MyComponent" instead of type?
Dynamically load components in Angular 12 and 13 In the html template, there is a with viewContainerRef. We use ViewChild('viewContainerRef') to obtain the ViewContainerRef. Moreover, we declare ComponentRef array to release the memory of FoodCardComponent in ngOnDestroy to avoid memory leaks.
Perhaps this will work
import { Type } from '@angular/core'; @Input() comp: string; ... const factories = Array.from(this.resolver['_factories'].keys()); const factoryClass = <Type<any>>factories.find((x: any) => x.name === this.comp); const factory = this.resolver.resolveComponentFactory(factoryClass); const compRef = this.vcRef.createComponent(factory);
where this.comp
is a string name of your Component like "MyComponent"
Plunker Example
To do it working with minification see
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