Best Way to Create Dynamic Components in Angular
Tags: angular, webdev, programming, typescript
Published: 2021-11-17 05:33:21

The article is originally published to my blog [here](https://stackblogger.com/dynamic-components-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](https://v13.angular.io/api/core/ViewContainerRef#createComponent) without creating an associated factory.

> Learn what are the new features and updates in Angular 13 [here](https://stackblogger.com/angular-13-features/).

### 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`

```typescript
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`

```html
<p>dynamic-components works!</p>
 
<ng-template dynamicChildLoader></ng-template>
```

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`

```typescript
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 created component using Ivy](https://cdn.stackblogger.com/wp-content/uploads/2021/11/image.png)

**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.

```typescript
@Input() customData: any;
```

`parent.component.ts`

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

```typescript
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 the parent component](https://cdn.stackblogger.com/wp-content/uploads/2021/11/image-1.png)

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.

The article is originally published to my blog [here](https://stackblogger.com/dynamic-components-angular/).

## 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](https://stackblogger.com/category/angular/).

Read how proper use of [RxJS Observables and Operators](https://stackblogger.com/tag/rxjs/) can improve your Website Speed.

Some [common points](https://stackblogger.com/5-best-ways-to-optimize-angular-for-scaling/) that can improve your Angular Website Speed you can’t imagine.