Angular how to dynamically inject a component to DOM

Notegiven the semver adopted from now on by Angular team, I will refer to all versions of Angular2+ as Angular. For the old Angular 1.x, I will use AngularJs

In this post, we’ll take a look on how to dynamically inject a component into the DOM using a directive as a placeholder and ViewContainerRef Angular class.

For simplicity, we will declare a new Angular component that later will be dynamically added/removed to/from the DOM:

Then we declare the directive used as a placeholder on the DOM where we want to inject the new component:

We add the directive on DOM in the place where the new component will be injected:

Finally, into the parent component, we add two functions, one who add the component, other who remove it:

This way we can dynamically add/remove components.

If you need an example, I added a working demo app on Github here.

 

If your company needs consulting on migration from Angular 1 to Angular 2/4/5 or training/update Angular knowledge, write me to contact@bogdancarpean.com

One thought on “Angular how to dynamically inject a component to DOM

Leave a Reply

Your email address will not be published. Required fields are marked *