Created
September 22, 2016 21:19
-
-
Save glendaviesnz/ffd929e9f48d06898cf1985e9822e01d to your computer and use it in GitHub Desktop.
Angular 2 dynamic component
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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