问题
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:
The event object:
By expanding this we get the unique parent id:
回答1:
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') 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
来源:https://stackoverflow.com/questions/52879324/angular-how-do-i-parse-the-objects-in-inside-event-path