Skip to content

Instantly share code, notes, and snippets.

@carmichaelize
Last active July 28, 2016 20:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save carmichaelize/25c68e89a829c230a28cd403533c4b4e to your computer and use it in GitHub Desktop.
Save carmichaelize/25c68e89a829c230a28cd403533c4b4e to your computer and use it in GitHub Desktop.
Angular2 component resolver example
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