Angular 2 动态组件点击事件

2022-01-21 00:00:00 javascript components angular

我正在尝试动态创建组件,但我想为其添加点击操作,但我不知道如何操作.我试图这样做:

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?

推荐答案

可以注入渲染器并使用

this.renderer.listen(widgetReference.location.nativeElement, 'click', (event) => { this.createNew(e);});

类似于 Angular2 - 捕捉/订阅动态添加的 HTML 中的(点击)事件

(widgetReference.location 提供ElementRef)

相关文章