How to dynamically create a component in Angular?
In Angular, a component can be created dynamically using ViewContainerRef and ComponentFactoryResolver (in Angular 13+ it is preferable to use just ViewContainerRef.createComponent).
Example for Angular 13+
typescript
import { Component, ViewChild, ViewContainerRef } from '@angular/core';
import { ChildComponent } from './child.component';
@Component({
selector: 'app-parent',
template: `<ng-template #container></ng-template>`
})
export class ParentComponent {
@ViewChild('container', { read: ViewContainerRef, static: true })
container!: ViewContainerRef;
createChild() {
// create the component dynamically
const componentRef = this.container.createComponent(ChildComponent);
componentRef.instance.title = 'Hello, dynamic component!';
}
}Explanation
<ng-template>serves as the insertion point for the dynamic component.ViewChild+ViewContainerRefprovide access to this insertion point.createComponentcreates a component instance and inserts it into the DOM.- Through
componentRef.instanceyou can set the component's properties after creation.
Conclusion: dynamically creating components allows rendering elements based on an event or condition, without declaring them in advance in the template.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.