Skip to content

Instantly share code, notes, and snippets.

@cakeinpanic
Last active August 8, 2017 20:51
Show Gist options
  • Save cakeinpanic/cf2692987cf3005d93e19fbfb2a27088 to your computer and use it in GitHub Desktop.
Save cakeinpanic/cf2692987cf3005d93e19fbfb2a27088 to your computer and use it in GitHub Desktop.
render custom component
@Component({
selector: 'inner-component',
template: '<div (click)="onClick()">{{someValue}}</div>'
})
export class InputComponent {
@Input() someValue: string;
@Output() onClick = new EventEmitter<any>();
}
@NgModule({
exports: [InnerComponent],
declarations: [InnerComponent]
})
export class InnerModule {}
@Component({
selector: 'wrapper-component',
template: '<span #customComponent></span>'
})
export class WrapperComponent {
@ViewChild('customComponent', {read: ViewContainerRef}) body: ViewContainerRef;
customComponentRef: ComponentRef<Component>;
constructor(@Inject(Compiler) private compiler: Compiler) {
}
renderComponent() {
this.compiler
.compileModuleAndAllComponentsAsync(InnerModule)
.then(factory => {
return factory.componentFactories
.find(x => x.componentType === InnerComponent);
})
.then((component) => {
this.customComponentRef = this.body.createComponent(component, 0);
// binding inputs
const {instance} = this.customComponentRef;
_.extend(instance, {someValue: 'text'});
// binding outputs
instance['onClick'].subscribe(() => {
console.log(`clicked`);
});
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment