Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To add components dynamically to a page in Angular 2, you can use the ComponentFactoryResolver class. Here are the steps to do this:

  1. Import the ComponentFactoryResolver class from '@angular/core'.
import { ComponentFactoryResolver } from '@angular/core';
  1. Inject the ComponentFactoryResolver into your component constructor.
constructor(private componentFactoryResolver: ComponentFactoryResolver) { }
  1. Define a ViewChild property for the container where you want to add the dynamic component. For example, if you want to add the dynamic component to a
    element with a #container reference:
@ViewChild('container', { read: ViewContainerRef }) container;
  1. Retrieve the component type from the API response. For example, if the component name is returned in a "componentName" field of the API response:
const componentType = this.getComponentType(componentName);
  1. Use the ComponentFactoryResolver to create a new instance of the component factory for the component type.
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(componentType);
  1. Use the container property to create a new instance of the component in the container.
const componentRef = this.container.createComponent(componentFactory);
  1. Set any inputs or outputs on the component instance as needed before it is rendered.
componentRef.instance.inputProperty = ...;
componentRef.instance.outputEvent.subscribe(...);

Here is an example implementation of these steps in a component:

import { Component, ComponentFactoryResolver, ViewChild, ViewContainerRef } from '@angular/core';
import { Api } from './api.service';
import { DynamicComponent } from './dynamic.component';

@Component({
  selector: 'app-root',
  template: `
    <div #container></div>
  `
})
export class AppComponent {
  @ViewChild('container', { read: ViewContainerRef }) container;

  constructor(private api: Api, private componentFactoryResolver: ComponentFactoryResolver) { }

  ngOnInit() {
    this.api.getComponentName().subscribe(componentName => {
      const componentType = this.getComponentType(componentName);
      const componentFactory = this.componentFactoryResolver.resolveComponentFactory(componentType);
      const componentRef = this.container.createComponent(componentFactory);
      componentRef.instance.inputProperty = ...;
      componentRef.instance.outputEvent.subscribe(...);
    });
  }

  private getComponentType(componentName: string) {
    switch (componentName) {
      case 'DynamicComponent': return DynamicComponent;
      // add other cases for other dynamic components
      default: throw new Error(`Invalid component type: ${componentName}`);
    }
  }
}