可以使用scrollDispatcher服务和ViewportRuler类来手动检测滚动事件,并根据需要更新覆盖层的位置。
在组件中引入以下服务:
import { ScrollDispatcher, ViewportRuler } from '@angular/cdk/overlay';
constructor(private scrollDispatcher: ScrollDispatcher, private viewportRuler: ViewportRuler) { }
在ngOnInit函数中订阅滚动事件和视口大小更改事件,并使用overlayRef.updatePosition()方法来更新覆盖层的位置。
ngOnInit(): void {
const scrollSubscription = this.scrollDispatcher.scrolled().subscribe(() => {
if (this.overlayRef && this.overlayRef.hasAttached()) {
this.overlayRef.updatePosition();
}
});
const resizeSubscription = this.viewportRuler.change().subscribe(() => {
if (this.overlayRef && this.overlayRef.hasAttached()) {
this.overlayRef.updatePosition();
}
});
this.subscriptions.push(scrollSubscription, resizeSubscription);
}
最后在组件销毁时取消订阅:
ngOnDestroy(): void {
this.subscriptions.forEach(s => s.unsubscribe());
}