简体   繁体   English

如何使用HostListener自定义元素? (角2)

[英]How to user HostListener for custom elements? ( angular 2)

I can use HostListener for document listening: 我可以使用HostListener进行文档侦听:

@HostListener('document:click', ['$event'])
someAction(event) {
    console.log('done');
}

How can I listen for click events for elements. 如何监听元素的click事件。 For example: 例如:

<span class="someClass"></span>

@HostListener('click', ['$event']) is to listen for events on the host element itself. @HostListener('click', ['$event'])用于侦听主机元素本身上的事件。 There is no other use case they can be used for. 没有其他可用的用例。

One exception are global events like you used with global event targets like window: , document: , or body . 一个例外是全局事件,例如您与诸如window:document:body类的全局事件目标一起使用的事件。

To listen on arbitrary elements use 聆听任意元素使用

<span class="someClass" (click)="someAction($event)"></span>

The answer of Gunter is correct, but you can make a Directive with a HostListener for more global sense of use (like a favorite/like button). Gunter的答案是正确的,但是您可以使用HostListener来制定指令,以获得更全面的使用感(例如“收藏夹” /“喜欢”按钮)。

@Directive({
selector: '.favorite'
})
class FavoriteDirective(){
 @HostListener('click', ['$event.target']) onClick(_element) {
    ...
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM