Skip to content

Instantly share code, notes, and snippets.

@glendaviesnz
Created September 22, 2016 21:19
Show Gist options
  • Save glendaviesnz/ffd929e9f48d06898cf1985e9822e01d to your computer and use it in GitHub Desktop.
Save glendaviesnz/ffd929e9f48d06898cf1985e9822e01d to your computer and use it in GitHub Desktop.
Angular 2 dynamic component
import { Component, Input, ViewChild, OnInit, ComponentFactoryResolver, ComponentFactory, ComponentRef } from '@angular/core';
import { ViewContainerRef } from '@angular/core';
import { SitesList } from './sites/sites-list.component';
import { UserList } from './users/user-list.component'
const components = {
SitesList,
UserList
}
@Component({
selector: 'dynamic-component',
template: '<div #container></div>'
})
export class DynamicComponent implements OnInit {
@Input() componentName: string;
// Inject the dynamic component onto the DOM
@ViewChild("container", {read: ViewContainerRef}) container: ViewContainerRef;
private componentReference:ComponentRef<any>;
constructor(
private viewContainer: ViewContainerRef,
private resolver:ComponentFactoryResolver
) { }
ngOnInit() {
let componentFactory = this.resolver.resolveComponentFactory(components[this.componentName]);
this.componentReference = this.container.createComponent(componentFactory);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment