Create component from a string

2019-09-20 05:50发布

问题:

I have some components that I'd like to add to my page dynamically.

I have their name in a config file config.json, currently the typescript classname MySuperComponent. I can put anything I want in my config file is the class name is not suited.

I've tried some code with component resolver, but I can't pass a string to it.

This works:

this.resolver.resolveComponent(MySuperComponent)

This doesn't:

this.resolver.resolveComponent("MySuperComponent")

How can I instanciate (and inject) a component from a String ?

回答1:

You can set up a map and provide it by a service that translates from string to type

import {MySuperComponent} from './MySuperComponent';

@Injectable() 
class ComponentTypes {
  types = {
    MySuperComponent: MySuperComponent
  };
  toType(name:string) {
    return types[name];
  }
}

where you use it

@Component({
  ...
  providers: [ComponentTypes],
})
class SomeComponent {
  constructor(private componentTypes:ComponentTypes) {}

  addDynamicComponent() {
    ...
    this.resolver.resolveComponent(this.componentTypes.toType("MySuperComponent"))

  }
}

See also Angular2, manually resolve a type by string/name



回答2:

Following the Pankaj's comment, you could use System.import:

let componentPath = (...)
let componentName = 'MySuperComponent';
System.import(componentPath)
        .then(fileContents => {
            return fileContents[componentName]
        })
        .then(component => {
            this.resolver.resolveComponent(component);
        });