Creating a Dynamic Component with a Directive

Ole Ersoy
1 min readFeb 7, 2019
Photo by Nick Fewings on Unsplash

Scenario

We need to create a dynamic component using a directive. The component should be rendered within the element that the directive is attached to.

For example if we did <p directive>Then the component is created inside this p elemment</p> .

Approach

In order to do this we need a ViewContainerRef . Simply constructor inject it into the directive like this:

constructor(vc: ViewContainerRef) {
//The ViewContainerRef is bound to the p element
}

If we now do vc.createComponent(...) the components view will be rendered inside the p element.

For an example of how to create a dynamic component see:

Side Note

If we inject an ElementRef into our directive like this:

contructor(el: ElementRef, view: ViewContainerRef) {
console.log(el.nativeElement === view.element.nativeElement); // prints TRUE
}

We see that the directives el is the same as the directives view .

--

--