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:

import { Component } from '@angular/core';

@Component({
  selector: 'app-injected',
  templateUrl: `<div>Another component was added</div>`,
  styleUrls: ['./injected.component.css']
})
export class InjectedComponent {

}

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

import { Directive, ViewContainerRef } from '@angular/core';

@Directive({
  selector: '[appInject]'
})
export class InjectDirective {

  constructor(public viewContainerRef: ViewContainerRef) { }

}

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

<div class="where_you_want_to_inject">    
  <ng-template appInject></ng-template>
</div>

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

import { Component, ViewChild, ComponentFactoryResolver } from '@angular/core';
import { InjectDirective } from '../inject.directive';
import { InjectedComponent } from '../injected/injected.component';

@Component({
  selector: 'app-parent',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.css']
})
export class ParentComponent {

  @ViewChild(InjectDirective) injectComp: InjectDirective;

  constructor(private _componentFactoryResolver: ComponentFactoryResolver) {
  }

  public addComp() {
    const componentFactory = this._componentFactoryResolver.resolveComponentFactory(InjectedComponent);
    const viewContainerRef = this.injectComp.viewContainerRef;
    const componentRef = viewContainerRef.createComponent(componentFactory);
  }

  public removeComp() {
    const componentFactory = this._componentFactoryResolver.resolveComponentFactory(InjectedComponent);
    const viewContainerRef = this.injectComp.viewContainerRef;
    const componentRef = viewContainerRef.remove();
  }

}

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 *