将对象注入动态创建的组件构造函数中

时间:2019-04-18 00:03:32

标签: angular angular7

我有一个Angular 7组件:

window.$nuxt.$store

我正在使用export class HelloComponent { constructor(private data: any) {} } 动态创建它:

ComponentFactoryResolver

如何在HelloComponent构造函数中注入private create(data: any) { var componentRef = this.componentFactoryResolver .resolveComponentFactory(HelloComponent) .create(this.injector); this.appRef.attachView(componentRef.hostView); var element = (componentRef.hostView as EmbeddedViewRef<any>).rootNodes[0] as HTMLElement; } 对象?

1 个答案:

答案 0 :(得分:1)

您必须为此使用自定义注射器

const injector: Injector = ReflectiveInjector.resolveAndCreate(
[{
     provide: 'config', useValue: { 
     value: 'Any value or object here'}
}]);

在您的组件中使用此

export class HelloComponent {
  constructor(@Inject('config') private data: any) {}
}