5

Now this is a complicated issue to explain, I will try my best.

I have a popover from which I want to uniquely identify a click event if it is from inside or outside the popover.

My first approach: I enveloped the entire popover with a div with an id, say "unique".

So, I bound the click event with a host listener for which I will get an event object. So, if I traverse the event.path --- this contains an array of objects --- inside one of the indexes of these objects lies a field id, which will give me the name of my id.

Note: this index will be always dynamic- but the id will be guaranteed in one of the index. I need to traverse till this id. Please help. I have attached some images for better visualization.

The host listener:

enter image description here

The event object:

enter image description here

By expanding this we get the unique parent id:

enter image description here

1 Answer 1

2

The path property on an event is only available in Chrome, and is undocumented. You can use the equivalent composedPath(), but IE and Edge do not support this yet.

If you don't care about that support you can do something like this. See how I used ViewChild to get the correct element. It's better this way, so you don't need to use silly IDs:

@ViewChild('elementYouCareAbout',  {read: ElementRef}) element: ElementRef<any>;   

@HostListener('document:click', ['$event']) onClick(event: MouseEvent) {
  const isInside = event.composedPath().includes(this.element.nativeElement);
}

Now if you do care about IE and Edge support, there is another way to check it, and that's by using the parentElement property:

@ViewChild('elementYouCareAbout') element: ElementRef<any>;   

@HostListener('document:click', ['$event']) onClick(event: MouseEvent) {
  let isInside = false;
  let target = event.target;
  while(target && !isInside) {
    isInside = this.element.nativeElement === target;
    target = target.parentElement;
  }

  // if inside than isInside is true
}

this code is not tested though, so be advised

Sign up to request clarification or add additional context in comments.

3 Comments

The path property is now in Edge, still not in Mozilla
why not use:this.element.nativeElement.contains(event.target as HTMLElement)?:NOTE If we define the hostListener in the "popover" we can inject the ElementRef in the constructor and check if contains the event.target
@Eliseo yep, that's the way to do it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.