angular - DOM .contains() 找不到元素且 parentNode 为空

angular - DOM .contains() cannot find element and parentNode is null

我想这里的很多人都熟悉 .contains() 函数,它用于检查 Element/Node 是否是父节点的子节点。

下面是一个简单的 Angular 使用 .contains() 的点击外部指令。

    constructor(private _elRef: ElementRef) {
    }

    @Output()
    public clickOutside = new EventEmitter();

    @HostListener('document:click', ['$event.target'])
    public onClick(targetElement) {
        const clickedInside = this._elRef.nativeElement.contains(targetElement);
        if (!clickedInside) {
            this.clickOutside.emit(null);
        }
    }

这很好用,直到我单击任何图像元素时,.contains() 实际上找不到它 & returns 而是 false。示例:

<div id="parent">
    ...
    <button>
        <ng-container>
            <img id="child" src="...">
        </ng-container>
    </button>
    ...
</div>

知道为什么找不到图像元素吗?

当 HTML 元素位于 ng-container 块内时,该特定 DOM 元素的 parentNode 属性 为 null。我怀疑是因为ng-container块不会生成到DOM,所以对其父节点的引用被破坏了。

这使得DOM.contains()函数无法工作(因为它是基于遍历Node Tree)

我会在 Angular GitHub 报告这个问题。