3

I have the following code:

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;
  }

}

In the function isSideBarElement I want to check if the target of the event is a child of the component.

Any sugestions?

Ricardo Rocha
  • 14,612
  • 20
  • 74
  • 130

2 Answers2

9

Inject ElementRef (represents reference to host html element) inside constructor:

constructor(private eleRef: ElementRef) {}

And inside isSideBarElement check if target is its descendant:

private isSideBarElement(event): boolean{
  let element: HTMLElement = event.target as HTMLElement;
  return (this.eleRef.nativeElement as HTMLElement).contains(element)
}
cezn
  • 2,705
  • 11
  • 16
0

Pass the elementRef of the component as parent and event.target as the child.

   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;
  }
Franklin Pious
  • 3,670
  • 3
  • 26
  • 30