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:
import { ComponentFactoryResolver } from '@angular/core';
constructor(private componentFactoryResolver: ComponentFactoryResolver) { }
@ViewChild('container', { read: ViewContainerRef }) container;
const componentType = this.getComponentType(componentName);
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(componentType);
const componentRef = this.container.createComponent(componentFactory);
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}`);
}
}
}