Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/excel/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 如何将单击处理程序附加到投影的内容元素_Angular_Viewchild_Ng Template - Fatal编程技术网

Angular 如何将单击处理程序附加到投影的内容元素

Angular 如何将单击处理程序附加到投影的内容元素,angular,viewchild,ng-template,Angular,Viewchild,Ng Template,我使用内容投影将一个按钮放入组件中 <hello name="{{ name }}"> <button #btn>Click Me</button> </hello> 不幸的是,当我在ngAfterViewInit中登录this.btn时,我得到了一个“未定义”的消息。即使它真的起作用了,我想一定有比访问本机元素更具角度的方式来连接侦听器 实现这一目标的最佳方式是什么 stackblitz示例:您可以使用@ContentChild或@Cont

我使用内容投影将一个按钮放入组件中

<hello name="{{ name }}">
  <button #btn>Click Me</button>
</hello>
不幸的是,当我在ngAfterViewInit中登录this.btn时,我得到了一个“未定义”的消息。即使它真的起作用了,我想一定有比访问本机元素更具角度的方式来连接侦听器

实现这一目标的最佳方式是什么


stackblitz示例:

您可以使用
@ContentChild
@ContentChildren
访问组件内部的投影子组件:

@Component({
  selector: 'hello',
  template: `
  <h3>Hello {{name}}!</h3>
  <ng-content></ng-content>
  `
})
您可以在这里阅读更多关于它的内容,以及与
@ViewChild
@ViewChildren

在访问您的孩子之后,您可以使用rxjs和操作符等工具来获取点击事件

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

为什么不在按钮上
(单击)
?如果我在按钮html中添加(单击)=“onClick()”,它将尝试绑定到组件的父onClick方法为什么需要绑定到子组件?我希望不同的父级为组件提供不同的模板自定义。绑定到子级将允许我重用处理程序代码。
fromEvent(this.mycontentchildelement, 'click').subscribe((event) => console.log('got clicked', event));