2

Can we inject different provider while loading components dynamically?

my-component

  @Component({
     moduleId: module.id,
     selector: "my-component",
     template: "<div>my-component</div>",
     providers: [MyComponentService]
  })
  export class MyComponent{

     constructor(private ds: MyComponentService) {
        super();
     }    
   }

some where else,

     this._cr.resolveComponent(MyComponent).then(cmpFactory => {
        let instance: any = this.testComponentContainer.createComponent(cmpFactory).instance;
    });

so in above code, while resolving MyComponent, provider for this MyComponentService will also be resolved, can we resolve it differently based upon some switch?

Madhu Ranjan
  • 17,334
  • 7
  • 60
  • 69

1 Answers1

3

ViewContainerRef.createComponent

createComponent(componentFactory: ComponentFactory<C>, index?: number, injector?: Injector, projectableNodes?: any[][]) : ComponentRef<C>

has an injector parameter. If you pass one this one is used to resolve providers. I don't think you can override providers added to the @Component() decorator though.

You can create a new injector Injector

let injector = ReflectiveInjector.resolveAndCreate([Car, Engine])

and pass this injector or you can inject the injector to the component that calls ViewContainerRef.createComponent and create a child injector.

constructor(private injector:Injector) {}

Injector is the generic base class ReflectiveInjector is a concrete implementation.

let resolvedProviders = ReflectiveInjector.resolve([Car, Engine]);
let child = ReflectiveInjector.fromResolvedProviders(resolvedProviders, this.injector);

This way the providers that are available to the current component are passed along and Car, and Child are added. Therefore providers that child can't resolve (others than Car and Engine) are tried to resolve from the parent injector.

Plunker example

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • so is it good to assume if i don't add provider parameter, and use injector then component factory will inject MyComponentService while loading component dynamically? – Madhu Ranjan Jun 09 '16 at 19:49
  • I had expected that the parent injector would be passed along when none is passed (not tested). If this doesn't work then just inject it to the current component and forward it to `createComponent(...)` or if you want add additional providers, then create a child injector. – Günter Zöchbauer Jun 09 '16 at 19:52
  • when i try to use this.testComponentContainer.createComponent(cmpFactory,, injector). Any suggestions? – Madhu Ranjan Jun 09 '16 at 20:09
  • Plunker you have added is not working, I am seeing some console errors. – Madhu Ranjan Jun 22 '16 at 14:04
  • Sorry for that. The Plunker was broken in two ways. One was caused by me. The other seems to be caused by Angular updates. I updated the Plunker. – Günter Zöchbauer Jun 22 '16 at 14:30