How to handle/provide @Input
and @Output
properties for dynamically created Components in Angular 2?
The idea is to dynamically create (in this case) the SubComponent when the createSub method is called. Forks fine, but how do I provide data for the @Input
properties in the SubComponent. Also, how to handle/subscribe to the @Output
events the SubComponent provides?
Example: (Both components are in the same NgModule)
AppComponent
@Component({
selector: 'app-root'
})
export class AppComponent {
someData: 'asdfasf'
constructor(private resolver: ComponentFactoryResolver, private location: ViewContainerRef) { }
createSub() {
const factory = this.resolver.resolveComponentFactory(SubComponent);
const ref = this.location.createComponent(factory, this.location.length, this.location.parentInjector, []);
ref.changeDetectorRef.detectChanges();
return ref;
}
onClick() {
// do something
}
}
SubComponent
@Component({
selector: 'app-sub'
})
export class SubComponent {
@Input('data') someData: string;
@Output('onClick') onClick = new EventEmitter();
}
ref.instance.someData = someData
. I am not sure if that is still the case though. – Kris Hollenbeck Nov 2 '16 at 14:26Reflection
directly Will try it :) – thpnk Nov 2 '16 at 14:38