简体   繁体   English

Angular 8:在鼠标单击事件后使用 HostListener 查找 DOM 元素

[英]Angular 8: Use HostListener to Find DOM Element after a Mouse Click event

How do I find the current DOM element anywhere in the page, after a mouse click?单击鼠标后,如何在页面中的任何位置找到当前的 DOM 元素? Currently trying to use HostListener in Angular 8.目前正在尝试在 Angular 8 中使用 HostListener。

@HostListener('click') onClick(){
    window.alert('Current DOM element is');
}

Set second parameter with $event.target使用$event.target设置第二个参数

@HostListener('click', ['$event.target']) onClick(e){
  window.alert('Current DOM element is');
  console.log(e);
}

You can also use ElementRef您还可以使用ElementRef

import { ElementRef } from '@angular/core';

constructor(private elementRef: ElementRef) {}

@HostListener('click') onClick(){
    console.log(this.elementRef.nativeElement);
}

Here is the link that explains that you can use a directive to detect a dom element and when it is present only then host listener should work. 是解释您可以使用指令来检测 dom 元素的链接,当它存在时,主机侦听器才应该工作。

Refer this:参考这个:

在此处输入图片说明

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

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