4

I have a component that dynamically loads another component using DynamicComponentLoader. However, the dynamic component needs to have a service injected. However, I'm unsure how to go about this. I see from Angular.io docs that DynamicComponentLoader accepts a ResolvedProvider array.

I've tried to get a provider by doing:

var provider = provide(ManagerService, {useExisting: ManagerService});
dcl.loadIntoLocation(this.data.template, this.er, "content",[provider]);

This doesn't seem to work. You can see an example on plunker.

On the plunker example, you can see that the Info component loads (because it isn't requiring the service) but the Alternate component won't load.

I'm a little confused because the service is being injected at the root component so I thought that it would automatically be injected on every child component when it was called for.

How do I get this service injected?

1 Answer 1

1

It shouldn't be any different than normal DI

this.dynamicComponentLoader.loadIntoLocation(MyComponent, this.elementRef, "content")


class MyComponent{
  constructor(someService:SomeService){}//injected here when instantiated
}

If your dynamically loaded component injects services in the constructor it works like normal DI.

Make sure the service is registered in some provider array though. Either at the component level or higher up in the chain (parent or bootstrap)

Sign up to request clarification or add additional context in comments.

1 Comment

That's what I thought. Did you have a look at the plunker example. As you can see, it clearly isn't being injected and as far as I can see, I've set everything up correctly.

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.