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

Recommended from Medium

React and an Open Mind

02 — Promises, promises (Welcome to JavaScript Async/Await)

21 Important Topics of Javascript | Javascript for Beginners

21 must-know topic of JavaScript

How to use Webpack code splitting with Vue.js

Node js Interview Question

React Studio + Xano No-code Backend Builder = ❤️

Basic Node Unit Testing with Jest

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

ACHARYA ANIL SURYAVANSHI

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

More from Medium

Angular — new emerging web technology

An Ode to AngularJS

An Introduction to LifeCycle hooks in Angular

RxJS Observables, a gentle introduction.