How To Create And Destroy Dynamic Components In Angular

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 

import { NgModule } from '@angular/core'; 
import { BrowserModule } from '@angular/platform-browser'; 
import { AppRoutingModule } from './app-routing.module'; 
import { AppComponent } from './app.component'; 
import { dynamicrestoryComponent } from './dynamicrestory.component'; 
@NgModule({ 
  declarations: [ 
    AppComponent, 
    dynamicrestoryComponent 
  ], 
  entryComponents: [ dynamicrestoryComponent ], 
  imports: [ 
    BrowserModule, 
    AppRoutingModule 
  ], 
  providers: [], 
  bootstrap: [AppComponent] 
}) 
export class AppModule { } 

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. 

// Create a factory for dynamicrestoryComponent. 
const new_component_factory = this.resolver.resolveComponentFactory(dynamicrestoryComponent); 

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. 

// Create a component using the factory. 
this.componentRef = this.alertContainer.createComponent(new_component_factory); 

The ComponentRef of the newly created component and call the clear() method of ViewContainerRef destroys the existing view in the container. 

// Clear the container alertContainer: ViewContainerRef; 
this.alertContainer.clear(); 

Next in the app.component,ts page copy code in the below  

import {
    Component,
    ViewChild,
    ViewContainerRef,
    ComponentFactoryResolver,
    ComponentRef
} from '@angular/core';
import {
    dynamicrestoryComponent
} from './dynamicrestory.component';
@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent {
    @ViewChild('messageContainer', {
        read: ViewContainerRef
    })
    alertContainer!: ViewContainerRef;
    componentRef!: ComponentRef < dynamicrestoryComponent > ;
    constructor(private resolver: ComponentFactoryResolver) {}
    createComponent(componentname: string) {
        // Clear the container. 
        this.alertContainer.clear();
        // Create a factory for MessageComponent. 
        const factory = this.resolver.resolveComponentFactory(dynamicrestoryComponent);
        // Create a component using the factory. 
        this.componentRef = this.alertContainer.createComponent(factory);
        // Pass the value for @Input properties using a component reference instance method. 
        this.componentRef.instance.dynamicrestory_msg = componentname + " " + "component";
        alert(componentname + " " + "component" + " " + "created successfully");
    }
    destroyComponent() {
        // destroy a component using the componentRef. 
        this.componentRef.destroy();
        alert("component" + " " + "destroy successfully");
    }
}

Add the destroy component. When we need to dynamically remove the component need to be please refer to the below clear function. 

destroyComponent() {
    // destroy a component using the componentRef. 
    this.componentRef.destroy();
    alert("component destroy successfully");
}

Please follow the app.component.html and dynamicrestoryComponent files codes below.

<h3 class="title">Test Dynamic Component Create & Destroy</h3> 
<button (click)="createComponent('home')">home component</button> 
<button (click)="createComponent('account')">account component</button> 
<button (click)="destroyComponent()">destroy component</button> 
<ng-template #TextContainer></ng-template> 

Dynamicrestory.component.ts 

import { Component, Input } from '@angular/core'; 
@Component({ 
  selector: 'dynamicrestory', 
  template: `<h2>{{dynamicrestory_msg}}</h2>`, 
}) 
export class dynamicrestoryComponent  { 
  @Input() 
    dynamicrestory_msg!: string; 
} 

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.