Miguel Moura
Miguel Moura

Reputation: 39474

Inject object into dynamically created component constructor

I have an Angular 7 component:

export class HelloComponent {
  constructor(private data: any) {}
}

And I am creating it dynamically using ComponentFactoryResolver:

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;

}

How to inject data object in HelloComponent constructor?

Upvotes: 2

Views: 315

Answers (1)

onik
onik

Reputation: 1631

You have to use custom injector for that

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

and in your component use this

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

Upvotes: 1

Related Questions