问题
I'm trying to create components dynamically but i want to add a click action to it and i don't know how. I was trying to do this:
constructor(public navCtrl: NavController, private resolver: ComponentFactoryResolver) {
this.lastSelectedResource = this.defaultImage;
}
public createNew() {
this.container.detach(0);
}
ngAfterContentInit() {
let widgetFactory = this.resolver.resolveComponentFactory(CreateComponent);
let widgetReference = this.container.createComponent(widgetFactory);
widgetReference.instance.click = this.createNew;
}
but isn't the way do that. Anybody knows how?
回答1:
You can inject the renderer and use
this.renderer.listen(widgetReference.location.nativeElement, 'click', (event) => { this.createNew(e);});
Similar to Angular2 - catch/subscribe to (click) event in dynamically added HTML
(widgetReference.location provides the ElementRef)
来源:https://stackoverflow.com/questions/40725620/angular-2-dynamic-component-click-event