DEV Community

midhul-m
midhul-m

Posted on

Dynamic loading of angular components

Usually when we load angular components in normal angular application, we used to call its selector name from component html template. So its clear in run time as well as in compile, which component is going to be rendered in that particular section in the DOM.

Image description

Above given is a sample which we use normally for loading an angular component inside another component or calling it from a root component.

Other than this we also could use router outlet, hence we could mentioned the component name in the route path based on the route name in the URL.

Image description

Once if we call this in the template, we can specify component name in RouterModules.ForRoot([path:'test',component:TestComponent])

So above given are the possible 2 ways of loading a component in common.

But based on the requirements and scenarios we face in our work life, situations may arise to load components dynamically.

It means, in the compile time, the angular compiler will not know which component is going to be rendered in the DOM.

we can take samples such as drag and drop. Suppose we have a requirement to create a widget dynamically. Given that there will be a blank

section and we need to drag and drop the template we need to that section in run time.

In such case, we need to specify component name dynamically within the drag and drop event and the component need to be rendered based on the template selection. Here consider each template means we drag and drop loads different angular components.

In angular/core node package, we do have a class called ComponentFactoryResolver, using which we can render a component at run time.

Below is the sample code of how we can render/load component dynamically. Here TestComponent is loaded dynamically and will be rendered inside the div element as shown in the HTML element.

Image description

Image description

Image description

Top comments (0)