Skip to main content

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

  1. <ng-template> serves as the insertion point for the dynamic component.
  2. ViewChild + ViewContainerRef provide access to this insertion point.
  3. createComponent creates a component instance and inserts it into the DOM.
  4. Through componentRef.instance you 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 ready
Premium

A concise answer to help you respond confidently on this topic during an interview.