首页 > 解决方案 > 为什么 cdk-overlay-container 没有添加到另一个 DOM 位置?

问题描述

我试图改变cdk-overlay-container放置的位置:

@Injectable({ providedIn: 'root' })
export class CustomOverlayContainer extends OverlayContainer {
    constructor(@Optional() @Inject(DOCUMENT) _document: any) {
        super(_document);
        this._createContainer();
    }

    getContainerElement() {
        return this._containerElement;
    }

    protected _createContainer(): void {
        const containerClass = 'cdk-overlay-container';
        const previousContainers = document.getElementsByClassName(containerClass);

        // If there is already a container (can happen in a Microfrontend scenario with
        // multiple self-contained Angular apps on the same website), reuse that. But
        // clean it up because it could be created while transitioning from server
        // to client (Angular Universal) and may be stale. Remove any additional containers.
        for (let i = 0; i < previousContainers.length; i++) {
            while (i === 0 && previousContainers[i].firstChild) {
                previousContainers[i].removeChild(previousContainers[i].firstChild);
            }

            if (i > 0 && !!previousContainers[i].parentNode) {
                previousContainers[i].parentNode.removeChild(previousContainers[i]);
            }
        }

        if (previousContainers.length > 0) {
            this._containerElement = previousContainers[0] as HTMLElement;
            return;
        }

        const container = document.createElement('div');
        container.classList.add(...[containerClass, 'ss']);
        let c = document.getElementById('map');

        c.appendChild(container);
        this._containerElement = container;
    }
}

然后我在根模块中使用它,如下所示:

{ provide: OverlayContainer, useExisting: CustomOverlayContainer },

无论如何,容器cdk-overlay-container被放置在身体中document.getElementById('map');

标签: angular

解决方案


推荐阅读