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

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.

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);

}

}

--

--

Software Engineer | Bharat Swabhiman Patanjali Social Activist | Speaker | Motivator | Yoga Trainer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
ACHARYA ANIL SURYAVANSHI

Software Engineer | Bharat Swabhiman Patanjali Social Activist | Speaker | Motivator | Yoga Trainer