gpt4 book ai didi

Angular 2+ : check if dom element is child of another dom element

转载 作者:搜寻专家 更新时间:2023-10-30 21:19:16 26 4
gpt4 key购买 nike

我有以下代码:

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

}

在函数 isSideBarElement 中,我想检查事件的目标是否是组件的子组件。

有什么建议吗?

最佳答案

在构造函数中注入(inject) ElementRef(表示对宿主 html 元素的引用):

constructor(private eleRef: ElementRef) {}

isSideBarElement 中检查目标是否是它的后代:

private isSideBarElement(event): boolean{
let element: HTMLElement = event.target as HTMLElement;
return (this.eleRef.nativeElement as HTMLElement).contains(element)
}

关于 Angular 2+ : check if dom element is child of another dom element,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50913222/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com