2

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?

2

1 Answer 1

1

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) {}
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.