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?

2 Answers 2

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) } 
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.