角度-如何解析event.path内部的对象 [英] Angular - How do I parse the objects in inside event.path
问题描述
现在这是一个很难解释的问题,我将尽力而为.
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.
我的第一种方法:我用div
和id
包围了整个弹出窗口,说独特".
My first approach: I enveloped the entire popover with a div
with an id
, say "unique".
因此,我将click事件与主机侦听器绑定,将为其获取事件对象.因此,如果我遍历event.path
--- 其中包含一个对象数组 ---在这些对象的索引之一内有一个字段id
,它将为我提供名称我的id
.
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
.
注意:该索引将始终是动态的-但在其中一个索引中将保证id
.我需要遍历此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.
主机侦听器:
事件对象:
通过扩展此代码,我们可以获得唯一的父ID:
By expanding this we get the unique parent id:
推荐答案
事件的path
属性仅在Chrome中可用,并且未记录.您可以使用等效的 composedPath()
,但是IE和Edge尚不支持此功能.
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.
如果您不关心该支持,则可以执行以下操作.看看我如何使用ViewChild
来获取正确的元素.这样更好,因此您不需要使用愚蠢的ID:
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);
}
现在,如果您确实关心IE和Edge支持,则还有另一种检查方法,那就是使用
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
这篇关于角度-如何解析event.path内部的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!