首页 > 解决方案 > 如何找到 Hostlistener 事件目标与 ElementRef 之间的关系?

问题描述

我需要知道,获取点击事件目标是我element来自viewChild或外部的孩子。这有可能找到吗?

我没有得到解决方案。

这是代码:

import { Component, ViewChild, HostListener, ElementRef } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {

 @ViewChild('child') element:ElementRef;

 @HostListener('document:click', ['$event.target']) onClick(event) {
      const parent = this.element.nativeElement;

      if(event is childOf(parent)) {
        //
      } else {
        //
      }

     console.log(parent, event);
  }

  name = 'Angular';

}

如何做到这一点?现场演示

有人帮帮我吗?

标签: angularangular8

解决方案


Node.contains()方法应该是您正在寻找的。

if(parent.contains(event)) {
  console.log('child')
} else {
  console.log('not a child')
}

分叉的 Stackblitz


推荐阅读