How to load component dynamically using component name in angular2?

后端 未结 5 1958
鱼传尺愫
鱼传尺愫 2020-11-29 03:58

I am currently loading angular components dynamically in my application using following code.

export class WizardTabCo         


        
5条回答
  •  一个人的身影
    2020-11-29 04:43

    i user anthor way to done this, may be helpful for you.

    1.first defined a class which use as name map componet and class RegisterNMC for moduleName map nmc

    export class NameMapComponent {
      private components = new Map();
    
      constructor(components: Component[]) {
        for (let i = 0; i < components.length; i++) {
          const component = components[i];
          this.components.set(component.name, component);
        }
      }
    
      getComponent(name: string): Component | undefined {
        return this.components.get(name);
      }
    
      setComponent(component: Component):void {
        const name = component.name;
        this.components.set(name, component);
      }
    
      getAllComponent(): { [key: string]: Component }[] {
        const components: { [key: string]: Component }[] = [];
        for (const [key, value] of this.components) {
          components.push({[key]: value});
        }
        return components;
      }
    }
    
    export class RegisterNMC {
      private static nmc = new Map();
    
      static setNmc(name: string, value: NameMapComponent) {
        this.nmc.set(name, value);
      }
    
      static getNmc(name: string): NameMapComponent | undefined {
        return this.nmc.get(name);
      }
    
    }
    
    type Component = new (...args: any[]) => any;
    
    1. in the ngMgdule file,you must put the components which be dynamically load in entryCompoent.

      const registerComponents = [WillBeCreateComponent]; const nmc = new NameMapComponent(registerComponents); RegisterNMC.setNmc('component-demo', nmc);

    3.in the container component

    @ViewChild('insert', {read: ViewContainerRef, static: true}) insert: ViewContainerRef;
    
      nmc: NameMapComponent;
      remoteData = [
        {name: 'WillBeCreateComponent', options: '', pos: ''},
      ];
    
      constructor(
        private resolve: ComponentFactoryResolver,
      ) {
        this.nmc = RegisterNMC.getNmc('component-demo');
    
      }
    
      ngOnInit() {
        of(this.remoteData).subscribe(data => {
          data.forEach(d => {
            const component = this.nmc.getComponent(d.name);
            const componentFactory = this.resolve.resolveComponentFactory(component);
            this.insert.createComponent(componentFactory);
          });
        });
      }
    

    it's fine, hopefully can help you ^_^!

提交回复
热议问题