Blog>
Snippets

Creating a Dynamic Component

Show how Renderer2 can be used to create a component dynamically and insert it into the view at runtime.
// Assume we're within an Angular component or directive
import { Renderer2, ElementRef, ComponentFactoryResolver, ViewChild, ViewContainerRef } from '@angular/core';

// Reference to the container where the dynamic component will be injected
@ViewChild('dynamicInsert', { read: ViewContainerRef }) dynamicInsertRef: ViewContainerRef;

constructor(
    private renderer: Renderer2,
    private factoryResolver: ComponentFactoryResolver
) {}

createDynamicComponent(component: any) {
  const componentFactory = this.factoryResolver.resolveComponentFactory(component);
  const componentRef = this.dynamicInsertRef.createComponent(componentFactory);

  // Any additional component setup goes here

  // Renderer2 can be used to modify the component's native element
  this.renderer.setStyle(componentRef.location.nativeElement, 'color', 'blue');
}
This code assumes we are within an Angular component or directive. It demonstrates how to dynamically create a new component using ComponentFactoryResolver and insert it into the view using a ViewContainerRef. It utilizes Renderer2 to apply additional styles (such as the color 'blue') to the newly created component's native element.