Last active
July 28, 2016 20:17
-
-
Save carmichaelize/25c68e89a829c230a28cd403533c4b4e to your computer and use it in GitHub Desktop.
Angular2 component resolver example
This file contains hidden or 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, ViewContainerRef, ComponentResolver, ComponentFactory} from '@angular/core'; | |
import {Child1Component} from './child1.component'; | |
import {Child2Component} from './child2.component'; | |
@Component({ | |
selector: 'parent', | |
template: ` | |
<div #target></div> | |
` | |
}) | |
export class ParentComponent { | |
@Input() child: string; | |
@Input() value: string; | |
children: Object; | |
childComponent: Object; | |
//Get where child compoent will be placed | |
@ViewChild('target', {read: ViewContainerRef}) target: ViewContainerRef; | |
constructor(private compiler: ComponentResolver) { | |
//Child components | |
this.children = {}; | |
this.children['child1'] = Child1Component; | |
this.children['child2'] = Child2Component; | |
} | |
ngAfterViewInit() { | |
//Get child component to be resolved (default to 'child1' to be safe) | |
let childComponent = this.children[this.child || 'child1']; | |
//Resolve child component | |
this.compiler.resolveComponent(childComponent).then((factory: ComponentFactory<any>) => { | |
this.childComponent = this.target.createComponent(factory); | |
//Pass in data to child component | |
this.childComponent.instance.value = this.value; | |
}); | |
} | |
ngOnChanges(){ | |
//Update child value when changes are made to parent component | |
if (this.childComponent) { | |
this.childComponent.instance.value = this.value; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment