问题出现的原因是菜单的位置计算有误,可以通过在组件中手动计算菜单位置来解决此问题。
首先,在组件中注入Overlay和ComponentFactoryResolver,并定义菜单触发器的位置。然后创建位置策略和显示菜单的OverlayRef,并将菜单的组件工厂解析为ComponentRef。
以下代码示例演示如何手动计算菜单位置:
component.ts:
import { Component, TemplateRef, ViewChild, ViewContainerRef, ElementRef } from '@angular/core';
import { Overlay, OverlayConfig, OverlayRef } from '@angular/cdk/overlay';
import { ComponentPortal } from '@angular/cdk/portal';
@Component({
selector: 'app-menu',
templateUrl: './menu.component.html',
styleUrls: ['./menu.component.scss']
})
export class MenuComponent {
@ViewChild('trigger', {read: ElementRef}) trigger: ElementRef;
@ViewChild('menu') menu: TemplateRef;
private overlayRef: OverlayRef;
constructor(private overlay: Overlay, private viewContainerRef: ViewContainerRef) {}
openMenu() {
if (!this.overlayRef) {
const positionStrategy = this.overlay.position()
.flexibleConnectedTo(this.trigger)
.withPositions([
{
originX: 'start',
originY: 'bottom',
overlayX: 'start',
overlayY: 'top',
offsetY: 5
}
]);
const overlayConfig = new OverlayConfig({
positionStrategy,
hasBackdrop: true,
backdropClass: 'cdk-overlay-transparent-backdrop',
scrollStrategy: this.overlay.scrollStrategies.block()
});
this.overlayRef = this.overlay.create(overlayConfig);
const menuPortal = new ComponentPortal(this.menu, this.viewContainerRef);
const menuRef = this.overlayRef.attach(menuPortal);
this.overlayRef.backdropClick().subscribe(() => this.overlayRef.detach());
}
}
}
在上述代码中,我们手动解析菜单组件并绑定位置策略,然后创建OverlayRef并显示菜单。做出这些更改之后,菜单应该正确显示在计算出的位置。