如何将点击处理程序附加到预计的内容元素

时间:2018-08-28 20:48:42

标签: angular viewchild ng-template

我正在使用内容投影将按钮放入组件中。

<hello name="{{ name }}">
  <button #btn>Click Me</button>
</hello>

以及组件:

@Component({
  selector: 'hello',
  template: `
  <h3>Hello {{name}}!</h3>
  <ng-content></ng-content>
  `
})

到目前为止很好...但是我现在想向该按钮添加(单击)事件侦听器,并且我希望处理程序位于接收计划内容的组件中。

我希望执行以下操作以访问本机元素,然后添加一个点击侦听器。

@ViewChild('btn') btn

不幸的是,当我在ngAfterViewInit中控制台登录this.btn时,我得到了一个“未定义”。而且,即使它确实起作用,我认为与访问本机元素相比,附加侦听器必须有更多角度的方法。

完成此任务的最佳方法是什么?

stackblitz示例:https://stackblitz.com/edit/angular-cj4bz1?file=src%2Fapp%2Fhello.component.ts

1 个答案:

答案 0 :(得分:3)

您可以使用@ContentChild@ContentChildren来访问组件内部的投影子对象。

您可以在此处详细了解@ViewChild@ViewChildren Content Child Docs的异同之处

访问儿童后,您可以使用rxjs和From Event运算符之类的东西来保留click事件。

fromEvent(this.mycontentchildelement, 'click').subscribe((event) => console.log('got clicked', event));

希望这会有所帮助

相关问题