Angular 2+:检查dom元素是否是另一个dom元素的子元素

时间:2018-06-18 15:50:06

标签: angular typescript

我有以下代码:

import { Component, OnInit, OnDestroy } from "@angular/core";

@Component({
  selector: 'sidebar-component',
  templateUrl: './sidebar.component.html'
})

export class SideBarComponent implements OnInit, OnDestroy {

  constructor() {}

  ngOnInit(): void {
      window["isSideBarElement"] = this.isSideBarElement;
  }

  ngOnDestroy(): void {}

  private isSideBarElement(event): boolean{
    let element: HTMLElement = event.target as HTMLElement;
    //mising code check if the target of the event is a child of the component
  }

  private getDOMElement(): HTMLElement{
    return document.getElementsByTagName("sidebar-component")[0] as HTMLElement;
  }

}

在函数isSideBarElement中,我想检查事件的目标是否是组件的子项。

任何sugestions?

2 个答案:

答案 0 :(得分:4)

在构造函数中注入ElementRef(表示对主机html元素的引用):

constructor(private eleRef: ElementRef) {}

isSideBarElement里面检查目标是否是它的后代:

private isSideBarElement(event): boolean{
  let element: HTMLElement = event.target as HTMLElement;
  return (this.eleRef.nativeElement as HTMLElement).contains(element)
}

答案 1 :(得分:0)

将组件的elementRef作为父项传递,将event.target作为子项传递。

   isDescendant(pParent: any, pChild: HTMLElement) {
    try {
      while (pChild !== null) {
        if (pChild === pParent) {
          return true;
        } else {
          pChild = (pChild.parentNode as HTMLElement);
        }
      }
    } catch (e) {
      console.warn('isDescendant ', e);
    }
    return false;
  }