Created
December 20, 2017 23:21
-
-
Save natmegs/8b1993a5b3456c39bd15384c1f062374 to your computer and use it in GitHub Desktop.
Final host 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, ViewChild, ViewContainerRef, ComponentFactoryResolver } from '@angular/core'; | |
import { DynamicComponent } from './dynamic.component'; | |
@Component({ | |
selector: 'host', | |
templateUrl: './host.component.html', | |
styleUrls: [ './host.component.css' ], | |
entryComponents: [DynamicComponent] | |
}) | |
export class AppComponent { | |
name = 'Dynamic'; | |
dynamicComponents = []; | |
@ViewChild('container', { read: ViewContainerRef }) container: ViewContainerRef; | |
get hasDynamicComponents() { | |
return this.container.length > 0; | |
} | |
constructor (private resolver: ComponentFactoryResolver) { | |
} | |
addComponent() { | |
let factory = this.resolver.resolveComponentFactory(DynamicComponent); | |
let inputs = { name: this.name }; | |
let component = factory.create(null); | |
Object.keys(inputs).map(input => { | |
component.instance[input] = inputs[input]; | |
}); | |
this.dynamicComponents.push(component); | |
this.container.insert(component.hostView); | |
} | |
removeComponent() { | |
this.dynamicComponents.pop().destroy(); | |
} | |
clearComponents() { | |
for(let component of this.dynamicComponents) { | |
component.destroy(); | |
} | |
this.dynamicComponents = []; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment