Best Way to Create Dynamic Components in Angular

Angular is a TypeScript based Open Source JavaScript framework. A situation like this happens most of the time where we need to create components dynamically. This article explains what is the best way to create dynamic components in Angular.

A component is a page in Angular. We will try to create it dynamically using the latest Ivy Component API and see how it works. Let’s start!

ComponentFactoryResolver is removed from latest Angular release. This article explains how to use Ivy API to create components dynamically.


Create Dynamic Components in Angular

We have seen in the latest Angular release, the use of ComponentFactoryResolver is removed. Ivy creates the opportunity to instantiate the component with ViewContainerRef.createComponent without creating an associated factory.

Learn what are the new features and updates in Angular 13 here.

Create ChildLoader Directive

The first step in creating a dynamic component is to set up a generic child loader directive. It will be responsible to load components dynamically wherever required in the project.

load-child.directive.ts


import { Directive, ViewContainerRef } from '@angular/core';

@Directive({
  selector: '[dynamicChildLoader]'
})
export class DynamicChildLoaderDirective {
  constructor(public viewContainerRef: ViewContainerRef) { }
}

DynamicChildLoaderDirective is a generic directive that will load the child components dynamically throughout the application. ViewContainerRef is instantiated publicly that will be used to apply the component.

Setup parent to load component dynamically

Create a parent component that will hold the child component dynamically.

parent.component.html


dynamic-components works!

Create a ng-template to hold the dynamic child component. dynamicChildLoader is used to apply the component dynamically. You can use it at any other place as well as per your requirement. It will create the component from ts file.

parent.component.ts


import { Component, OnInit, ViewChild } from '@angular/core';
import { DynamicChildComponent } from './dynamic-child/dynamic-child.component';
import { DynamicChildLoaderDirective } from './load-child.directive';

@Component({
  selector: 'app-parent',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.scss']
})
export class ParentComponent implements OnInit {
  @ViewChild(DynamicChildLoaderDirective, { static: true }) dynamicChild!: DynamicChildLoaderDirective;
  constructor() { }

  ngOnInit(): void {
    this.loadDynamicComponent();
  }

  private loadDynamicComponent() {
    this.dynamicChild.viewContainerRef.createComponent(DynamicChildComponent);
  }
}

Initialize a ViewChild of DynamicChildLoaderDirective type. Create the dynamic component using viewContainerRef from DynamicChildLoaderDirective directive.

Output

Run the application and check the browser. You can see the child component is loaded dynamically.

Dynamically create component using Ivy
Dynamically created component using Ivy

Note: It does not require destroying dynamically loaded components. The new Ivy API does it itself.

Create dynamic components in Angular with Parameters

So far we have learnt how to create components dynamically using Angular new API. It’s time to pass parameters to dynamically created components. Let’s see how to implement it.

child.component.ts

Declare an @Input variable to receive custom data from the parent.


@Input() customData: any;

parent.component.ts

Pass the data from parent component at the time of instantiating the dynamic component.


const componentRef = this.dynamicChild.viewContainerRef.createComponent(DynamicChildComponent);
componentRef.instance.customData = {
  test: 'test key',
  value: 'test value'
}

Assign the created instance in a local variable componentRef. Access the child component’s customData variable using instance. Pass the custom data in the variable. You can pass multiple data by creating multiple @Input variables in the child component.

Custom data sent from parent component
Custom data sent from the parent component

The custom data is received at child component that was sent from the parent at the time of creating component instance.

After Angular’s latest release, this is probably the best way to create a component dynamically in Angular. We do not need to destroy dynamically created components explicitly. Angular’s new API does it itself.

Conclusion

That’s it! We learnt how to create a dynamic component in Angular with the New API without using ComponentFactoryResolver. It also shows how to pass parameters to dynamically created components in Angular.

Check other Angular related articles here.

Read how proper use of RxJS Observables and Operators can improve your Website Speed.

Some common points that can improve your Angular Website Speed you can’t imagine.

1 thought on “Best Way to Create Dynamic Components in Angular

  1. Hey!
    Could you help me?
    Why doesn’t we need destroy dynamic component on OnDestroy hook?
    I didn’t find an information about this in angular docs and GitHub

Leave a Reply

Your email address will not be published. Required fields are marked *