Created
March 16, 2017 13:05
-
-
Save tenphi/94b8732d894ce7cec088738c7201e79e to your computer and use it in GitHub Desktop.
dynamic-component.ts
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, ViewContainerRef, ComponentRef, ComponentFactoryResolver, ViewChild, Type, Input, Compiler } from '@angular/core'; | |
// Helper component to add dynamic components | |
@Component({ | |
selector: 'tnp-component-injector', | |
template: `<div></div>` | |
}) | |
export class ComponentInjector { | |
@Input() component: Type<Component>; | |
@Input() props: Object = {}; | |
cachedComponent: Type<Component>; | |
componentRef: ComponentRef<Component>; | |
private isViewInitialized:boolean = false; | |
constructor(private componentFactoryResolver: ComponentFactoryResolver, private _viewContainerRef: ViewContainerRef) {} | |
updateComponent() { | |
if(!this.isViewInitialized) { | |
return; | |
} | |
if (this.cachedComponent !== this.component) { | |
if(this.componentRef) { | |
this.componentRef.destroy(); | |
} | |
let factory = this.componentFactoryResolver.resolveComponentFactory(this.component); | |
this.cachedComponent = this.component; | |
this.componentRef = null; | |
setTimeout( () => { | |
this.componentRef = this._viewContainerRef.createComponent(factory); | |
Object.assign(this.componentRef.instance, this.props); | |
}, 0); | |
} | |
if (this.componentRef) { | |
Object.assign(this.componentRef.instance, this.props); | |
} | |
} | |
ngOnChanges() { | |
this.updateComponent(); | |
} | |
ngAfterViewInit() { | |
this.isViewInitialized = true; | |
this.updateComponent(); | |
} | |
ngOnDestroy() { | |
if(this.componentRef) { | |
this.componentRef.destroy(); | |
} | |
} | |
} |
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 { NgModule } from '@angular/core'; | |
import { BrowserModule } from '@angular/platform-browser'; | |
import { ComponentInjector } from './component-injector'; | |
@NgModule({ | |
declarations: [ | |
ComponentInjector | |
], | |
imports: [ | |
BrowserModule, | |
], | |
exports: [ | |
ComponentInjector | |
], | |
entryComponents: [] | |
}) | |
export class ComponentInjectorModule { | |
constructor() {} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment