Angular: Load Multiple Dynamic Component in Page

Angular Dynamic Custom Loader on HTML element
Dhara Tank
14-Feb-2020
Reading Time: 4 minutes

In this tutorial article, we’ll learn how we can we load different component in page using Angular 8.

Prerequisites:

  1. Prior knowledge of TypeScript.
  2. Prior knowledge of JavaScript.
  3. Visual studio code.
  4. A development machine with Node 8.9+ & NPM 5.5.1+ installed.

Step-by-Step Tutorial of Loading Multiple Dynamic Component in One Page using Angular

Step 1: Installing Angular CLI 8

First step, where we’ll have to install latest version of Angular CLI.

$ npm install -g @angular/cli

Step 2: Creating your Angular 8 Project

  • In this second step, we will use Angular CLI to start our Angular Project
  • Go to CMD or Terminal and use this command:
$ ng new custom-loader
  • This CLI will ask you “whether you would like to add Angular routing?” Say Yes.
  • It will ask “which stylesheet format you would like to use?”. Choose CSS.
  • Now your project is ready Angular CLI will generate required files and folders along with NPM packages and routing too.
  • Now open your project in Visual studio code and go to your root folder and run the local development server using below command:
$ npm start
Angular CLI Installation CMD Image
Angular CLI Installation CMD Image

Now run localhost:4200/ in your browser.

Step 3: Add Different Components

  • Use this command
$ ng g c company-management
  • company-management – Parent Component
  • And create other child components. (Office,Customer,Employee)
customer component html file screenshot
customer component html file screenshot

Step 4: Add Directive for loading Component

Use this command

$ ng g directive company-tab
company tab directive ts file screenshot
company tab directive ts file screenshot
  • The directive decorator’s configuration property specifies the directive’s CSS attribute selector, [active-tab].
  • It’s the brackets ([]) that make it an attribute selector. Angular locates each element in the template that has an attribute named appActiveTab and applies the logic of this directive to that element.

ViewContainerRef – A container where one or more views can be attached to a component.

  • Embedded views (created by instantiating a TemplateRef with the createEmbeddedView() method).

Step 5: How to use Directives for load child Component

  • Open app.component.html page and add this selector (Parent Component).
<app-company-management></app-company-management>
  • set child-component in entryComponents.
  • An entryComponent is any component that Angular loads imperatively, (which means you’re not referencing it in the template), by type.
  • You specify an entry component by bootstrapping it in an NgModule, or including it in a routing definition.
  • entryComponents should be available just like if the module is imported. Render entryComponents of child modules at root level.
entryComponents Screenshot
entryComponents Screenshot
  • Below is company-management Component HTML page/file Code
company-management Component HTML file Code
Screenshot of company-management Component HTML file
  • ng-template –  It represents an Angular template: this means that the content of this tag will contain part of a template, that can be then composed together with other templates in order to form.
  • We are using it as a partial view. <ng-template> can be used with structural directive, ViewContainerRef etc.

Step 6: Add this code in company-management.component.ts.

import { Component, OnInit, ViewChild, ComponentFactoryResolver, ViewContainerRef } from '@angular/core';
import { isNullOrUndefined } from 'util';
import { EmployeeComponent } from '../employee/employee.component';
import { OfficeComponent } from '../office/office.component';
import { CustomerComponent } from '../customer/customer.component';
import { CompanyTabDirective } from '../company-tab.directive';

@Component({
  selector: 'app-company-management',
  templateUrl: './company-management.component.html',
  styleUrls: ['./company-management.component.css']
})
export class CompanyManagementComponent implements OnInit {
  _component: any;
  componentsList = [];

@ViewChild(CompanyTabDirective) tabHost: CompanyTabDirective;
constructor(
    private viewContainerRef: ViewContainerRef,
    private componentFactoryResolver: ComponentFactoryResolver,
) { }

ngOnInit() {
    // Default loaded Tab
  this.loadTabComponent("CUSTOMER");
}

loadTabComponent(_selectedTab: string) {
    // remove loaded Component
    if (!isNullOrUndefined(this.componentsList)) {
      this.componentsList.map((cm, i) => {
        let tmp = this.viewContainerRef;
        this.viewContainerRef.remove(this.viewContainerRef.indexOf(cm));
        this.viewContainerRef.remove(i);
        this.componentsList.splice(i, 1);
      });
    }

    this._component = "";
    if (_selectedTab == "CUSTOMER")
      this._component = CustomerComponent;
    else if (_selectedTab == "OFFICE")
      this._component = OfficeComponent;
    else if (_selectedTab == "EMPLOYEE")
      this._component = EmployeeComponent;

    this.viewContainerRef.detach();
    this.viewContainerRef.clear();
    const componentFactory = this.componentFactoryResolver.resolveComponentFactory(this._component);
    this.viewContainerRef = this.tabHost.viewContainerRef;

    let componentRef = this.viewContainerRef.createComponent(componentFactory);
    this.componentsList.push(componentRef);
  }
}

Output

Load Multiple Dynamic Component in Page Output Example GIF
Load Multiple Dynamic Component in Page Output Example GIF

Over To You!

Looking for a Sample Source Code? Here you go: GITHUB.

That’s it for now. Today you have learn how to load multiple dynamic content in one Page using Angular 8. Stay Connected for more tutorials, until than Happy Coding…

If you’re dealing with enterprise software or large-scale applications, getting expert assistance is necessary. You can hire dedicated Angular developers at Samarpan Infotech with more than 5 years of experience building enterprise applications.