33
loading...
This website collects cookies to deliver better user experience
ComponentFactoryResolver
is removed from latest Angular release. This article explains how to use Ivy API to create components dynamically.
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.
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.parent.component.html
<p>dynamic-components works!</p>
<ng-template dynamicChildLoader></ng-template>
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);
}
}
ViewChild
of DynamicChildLoaderDirective
type. Create the dynamic component using viewContainerRef
from DynamicChildLoaderDirective
directive.child.component.ts
@Input
variable to receive custom data from the parent.@Input() customData: any;
parent.component.ts
const componentRef = this.dynamicChild.viewContainerRef.createComponent(DynamicChildComponent);
componentRef.instance.customData = {
test: 'test key',
value: 'test value'
}
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.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.