Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load component dynamically using component name in angular2?

Tags:

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?

like image 927
Pankaj Kapare Avatar asked Oct 18 '16 18:10

Pankaj Kapare


People also ask

How do I load dynamic components in Angular 13?

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.


1 Answers

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

  • ng2 - dynamically creating a component based on a template
like image 105
yurzui Avatar answered Sep 28 '22 05:09

yurzui