【发布时间】:2019-05-24 20:17:35
【问题描述】:
我想在其中保留子组件的逻辑。然而,事件本身是从其父组件向下发生单击时发生的。
child.component.ts
@HostListener('document:click', ['$event']) onClick(event: MouseEvent) {
// get the parent component tag
const parentComponent = this.eRef.nativeElement.parentNode.parentNode;
for (let i = 0, j = parentComponent.length; i < j; i++) {
if (event.target == parentComponent[i]) {
console.log(parentComponent[i]);
}
}
我尝试了很多方法来遍历节点列表并比较 click event.target 以查看点击是在 parent 内部还是外部,但我似乎无法迭代 nodeList 并且不明白为什么.
我在 repro StackBlitz 上也尝试了许多其他方法。
也许有更好的方法来监视该组件的父级外部/内部的点击?另外,我不想将点击逻辑移动到父级,除非必须,否则逻辑不属于那里。
已修复:StackBlitz 已更新,其中包含我对使用 elementRef 遍历 DOM 的所有研究。 @Ritchie 也正确地遍历了 nodeList 并让它以这种方式工作。
【问题讨论】:
-
为什么不能把@HostListener 放在父级上,然后通过@Input 将流传递给子级?处理逻辑可以留在子级中。
标签: javascript angular events event-handling