I can use HostListener
for document listening:
@HostListener('document:click', ['$event'])
someAction(event) {
console.log('done');
}
How can I listen for click
events for elements. For example:
<span class="someClass"></span>
@HostListener('click', ['$event'])
is to listen for events on the host element itself. 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
.
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).
@Directive({
selector: '.favorite'
})
class FavoriteDirective(){
@HostListener('click', ['$event.target']) onClick(_element) {
...
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.