Angular 2 – Dynamically Injecting Components

Note this also covers upgrading from RC4 to RC5’s ComponentFactoryResolver.

I recently upgraded from RC4 to RC5 and as a result my dynamic component injection module failed due to ComponentResolver being deprecated. Of all the changes between RC4 and RC5, this seems to be the simplest deprecation step, but though I’d document it here.

Generating and Injecting Components

To dynamically inject componets, we need to use ComponentFactoryResolver to create both the factory and the component, as opposed to ComponentResolver and ComponentFactory in RC4.

Sort of, if you’ve put the ‘resolveComponentFactory’ code in the right place.

Injection and Life Cycle Hooks

You’ll need to hook into your components life cycle to correctly create and destroy your injected component – specifically ngOnInit and ngOnDestroy (in RC4 it was OK to use ngAfterViewInit rather than ngOnInit but this is no longer possible).

And that’s it, you have a component being injected and being rendered within our owners view.

Example Code

The code for the above is available on GitHub, and includes the diff when converting from RC4 to RC5. The GitHub code also shows how to change your dynamically injected component on the fly using ngOnChange to destroy the existing one and inject a new one on demand.

5 thoughts on “Angular 2 – Dynamically Injecting Components”

hi.. very helpful post.. but i have another use case where my template with #dynamicTarget is generated dynamically.. in that case when i use @viewChild.. i am not getting anything in the ViewContainerRef because its not yet generated. how can i fix this please help me

It really depends on how the container is being generated, when and by what. Without that kind of information giving you a solution is pretty tricky. Best bet would be to post up your specific source code examples on Stack Overflow and see what solutions are available.

Hi, first of all thank you for your post. I have a doubt. Is it possible to inject a dynamic templateUrl using this approach? Because, with the ComponentResolver I found how to do it but now it’s deprecated.