Last active
August 8, 2017 20:51
-
-
Save cakeinpanic/cf2692987cf3005d93e19fbfb2a27088 to your computer and use it in GitHub Desktop.
render custom 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
@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