这个问题通常是由于在应用中没有正确配置覆盖层容器而引起的。为了解决此问题,可以使用Angular的Overlay服务的create方法来创建一个覆盖层容器,并将其附加到现有的DOM元素。例如:
在组件中创建一个ViewContainerRef和OverlayRef:
import { Component, ViewChild, OnInit, OnDestroy } from '@angular/core'; import { Overlay, OverlayRef } from '@angular/cdk/overlay'; import { ComponentPortal } from '@angular/cdk/portal';
@Component({
selector: 'app-example-overlay',
template:
,
})
export class ExampleOverlayComponent implements OnInit, OnDestroy {
@ViewChild('overlayHost') overlayHost: ElementRef;
private overlayRef: OverlayRef;
constructor(private overlay: Overlay) {}
ngOnInit() { const positionStrategy = this.overlay .position() .global() .centerHorizontally() .centerVertically();
this.overlayRef = this.overlay.create({
hasBackdrop: true,
positionStrategy,
});
}
ngOnDestroy() { this.overlayRef.dispose(); }
showOverlay() { const portal = new ComponentPortal(SomeOverlayComponent); const componentRef = this.overlayRef.attach(portal); // 让覆盖层包含组件的区域 componentRef.instance.overlayHost = this.overlayHost; } }
在覆盖层组件中添加一个Input属性:
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-some-overlay',
template:
,
})
export class SomeOverlayComponent {
@Input() overlayHost: ElementRef;
constructor() {}
ngOnInit() { const nativeElement = this.overlayHost.nativeElement; // 将overlayContent附加到overlay