Angular 2 dynamic component click event

匆匆过客 提交于 2019-12-08 00:15:39

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!