Introduction
First, we need to install the Angular CLI. Once you have installed angular CLI and basic project setup, please follow the steps below.
Here I have added one more component additionally with basic angular project creation.
The name of the component is dynamicrestory.component.ts
Just follow the code below in the app.module.ts page
Commonly a component is loaded using the component selector in the component template that is identified at Angular compile time.
The component can also be loaded dynamically at runtime using ComponentFactory, ComponentFactoryResolver, and ViewContainerRef.
Those components which need to be loaded dynamically should also be configured in entryComponents metadata of @NgModule decorator in the app.module.ts file.
ComponentFactory
ComponentFactory is used to create instance of components.
ComponentFactoryResolver
ComponentFactoryResolver resolves a ComponentFactory for a specific component.
ViewContainerRef
ViewContainerRef represents a container we can able to attach one or more views.
Some important methods of ViewContainerRef and createComponent are used to attach embedded views based on TemplateRef. createComponent() component and inserts its host view into the view container at a specified index. In our dynamic component loader, it will be load component using createComponent() of ViewContainerRef.
The ComponentRef of the newly created component and call the clear() method of ViewContainerRef destroys the existing view in the container.
Next in the app.component,ts page copy code in the below
Add the destroy component. When we need to dynamically remove the component need to be please refer to the below clear function.
Please follow the app.component.html and dynamicrestoryComponent files codes below.
Dynamicrestory.component.ts
Once add the above codes please run and check the dynamic component creation using a click. Here I have run and added the steps please follow the images below.
![]()
After running the application, I am going to click the home component and the home component will create the home string pass while clicking params.
![]()
![]()
Next, create an account component at the time the home component will clear and created the account component.
![]()
![]()
Need to remove the component manual just click destroy button and removed all dynamic components.
![]()
Finally, we are able to do create and destroy dynamic components in our applications. I hope this article is most helpful for us.