Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to programmatically render a component in Angular?

As the title says is there a way to programmatically render (into a DOM element) a component in angular?

For example, in React I can use ReactDOM.render to turn a component into a DOM element. I am wondering if it's possible to something similar in Angular?

like image 488
Semo Avatar asked Aug 29 '26 15:08

Semo


2 Answers

At first you'll need to have a template in your HTML file at the position where you'll want to place the dynamically loaded component.

<ng-template #placeholder></ng-template>

In the component you can inject the DynamicFactoryResolver inside the constructor. Once you'll execute the loadComponent() function, the DynamicComponent will be visible in the template. DynamicComponent can be whatever component you would like to display.

import { Component, VERSION, ComponentFactoryResolver, ViewChild, ElementRef, ViewContainerRef } from '@angular/core';
import { DynamicComponent } from './dynamic.component';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html'
})
export class AppComponent  {
  @ViewChild('placeholder', {read: ViewContainerRef})
  private viewRef: ViewContainerRef;

  constructor(private cfr: ComponentFactoryResolver) {}

  loadComponent() {
    this.viewRef.clear();
    const componentFactory = this.cfr.resolveComponentFactory(DynamicComponent);
    const componentRef = this.viewRef.createComponent(componentFactory);
  }
}

Here is a Stackblitz.

What the loadComponent function does is:

  1. It clears the host
  2. It creates a so called factory object of your component. (resolveComponentFactory)
  3. It creates an instance of your factory object and inserts it in the host reference (createComponent)
  4. You can use the componentRef to, for example, modify public properties or trigger public functions of that components instance.
like image 123
Felix Lemke Avatar answered Aug 31 '26 06:08

Felix Lemke


Based on Felix's answer, the ComponentFactoryResolver is no longer required. Hence, the simplified version is

import { Component, VERSION, ViewChild, ElementRef, ViewContainerRef } from '@angular/core';
import { DynamicComponent } from './dynamic.component';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html'
})
export class AppComponent  {
  @ViewChild('placeholder', {read: ViewContainerRef})
  private viewRef: ViewContainerRef;

  loadComponent() {
    this.viewRef.clear();
    const componentRef = this.viewRef.createComponent(DynamicComponent);
  }
}
like image 44
Sen Alexandru Avatar answered Aug 31 '26 05:08

Sen Alexandru



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!