Angular Component Factory

Angular Component Factory. What is it? When it can be used and How to use it.

The pre-requisite to this blog is for you to have some background of the Angular Framework, what it does and have some working experience of it. If not, maybe this blog is not for you. Stay tuned, as we will have some blogs that walks you through Angular step by step. This tutorial expects for you to be of intermediate Angular level.

Angular Component Factory is exactly what the name implies, it is a factory that creates dynamic components. So, you can programatically create components rather than him them sitting in the template. When you see the template, you don’t find HTML code for them, however, when you open the ts file, you find some logic to bring them in or out of existence.

Why is that useful? Well, it is useful because sometimes, you would need to do exactly that. Remember, Angular is all about components. In the Javascript world, you would manipulate the DOM, by using some code like:-

 document.getElementById('container').innerHTML = 'new dom';

In Angular, you can still have the same outcome using the Renderer2 library, however, it will be far more maintainable to have your already baked code in a component and repeat it as you need to. This way, you can achieve better outcomes and get more maintainable code. A common real-world examples of that would be adding elements on the checkout while you are already in the checkout page. In this case, you will need to create a checkout tile and add it to the container. Maybe another good example would be an error handler component that would display your success, error and warning messages. It could be not such a bad idea to handle it by a dynamic component that will delete all other components

The question is then, how do you achieve this, building dynamic components. The answer is:

  1. In your template, you have a container with a reference. This can be done with a #.
<div #container></div>

2. Reference the element using ViewChild in your .ts file

@ViewChild("container", { read: ViewContainerRef }) container;

3. Use code similar to the below to create the component

let factory: ComponentFactory<any> = this.resolver.resolveComponentFactory( DynamicComponent ); let componentRef: ComponentRef<any> = this.container.createComponent( factory ); componentRef.instance.dynamicMessage = "dynamic message";

4. One thing to take note of is that when you create a component, you will have to destroy it yourself, since Angular will not take care of this for you. Use the following code to do so:-


You can see a living example of dynamic components in action by visiting the following link:

I hope you found this blog useful. Can’t wait to meet you in another one!

Leave a Reply

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