Sitemap

What is the dynamic component(dynamic loading)in Angular?

2 min readJun 5, 2021

--

Press enter or click to view image in full size

Angular boon us component factory for doing the same. Component Factory is base class for creating components dynamically. It have method resolveComponentFactory .And viewContainerRef for creating componentWe will use the viewContainerRef of base of the dynamic component.Which will create component using componentFactoryResolver.For Example We have to load one of the dynamic component on click.

Press enter or click to view image in full size
Press enter or click to view image in full size

Base Component template

<div>
<button (click)="onPress('ram')" class="bttn btn-primary">Ram Home</button>
<button (click)="onPress('shiv')" class="bttn btn-primary">Shiv Home</button>
</div>
<ng-template #container></ng-template>

Base Component class

import { Component, ComponentFactoryResolver, OnInit, ViewChild, ViewContainerRef } from '@angular/core';
import { RamComponent } from '../ram/ram.component';
import { ShivComponent } from '../shiv/shiv.component';
@Component({
selector: 'app-orders-list',
templateUrl: './orders-list.component.html',
styleUrls: ['./orders-list.component.scss']
})
export class OrdersListComponent implements OnInit {
@ViewChild( 'container',{read: ViewContainerRef}) container:ViewContainerRef;
componentRef:any;
constructor(private componentFactoryResolver:ComponentFactoryResolver) { }
ngOnInit(): void {
}
loadComponent(component){
this.unloadComponent();
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(component);
this.componentRef = this.container.createComponent(componentFactory);
}
unloadComponent(){
if(this.componentRef){
this.container.remove();
this.componentRef = null;
}
}
onPress(home){
if(home=='ram'){
this.loadComponent(RamComponent);
}else{
this. loadComponent(ShivComponent);
}
}

--

--

Anil Kumar
Anil Kumar

Written by Anil Kumar

Software Engineer| Angular Advocate | Cyclist