2

我想将一个角度 cdk 覆盖连接到我工具栏中的一个按钮。这就是我得到的:

覆盖按钮.html:

<button mat-menu-item #overlayButton (click)="showOverlay()"> open </button>

覆盖按钮.component

export class OverlayButtonComponent {
  @ViewChild('overlayButton') private _button: ElementRef;

  constructor(private _overlay: OverlayService) {}

  showOverlay() {
    this._overlay.open(DisplayedComponent,this._button);
  }
}

覆盖服务

export class OverlayService {
  constructor(private _overlay: Overlay) {}

  open(comp: ComponentType<any>, connectedTo:ElementRef) {
    const positionStrategy = this._overlay.position()
      .flexibleConnectedTo(connectedTo)
      .withPositions([{
        originX: 'start',
        originY: 'bottom',
        overlayX: 'start',
        overlayY: 'top',
      }]);

    const overlayRef = this._overlay.create({
      hasBackdrop: true,
      positionStrategy,
      scrollStrategy: this._overlay.scrollStrategies.reposition()
    });

    // Create ComponentPortal that can be attached to a PortalHost
    const filePreviewPortal = new ComponentPortal(comp);

    // Attach ComponentPortal to PortalHost
    overlayRef.attach(filePreviewPortal);

    overlayRef.backdropClick().subscribe(() => overlayRef.detach());
  }
}

问题是覆盖总是显示在浏览器的左上角。首先我认为viewChild有问题,也许elementRef未定义或类似的东西,但事实并非如此。我尝试了使用类似代码找到的每个教程,但没有任何效果。问题可能出在其他地方吗?

以下是它的说明:

叠加问题

4

2 回答 2

0

根据@joonas 评论,将您的 viewChild 代码修改为

 @ViewChild('overlayButton', {read: ElementRef}) private _button: ElementRef;

强制将 viewChild 读取为 ElementRef,从而传递到flexibleConnectedTo()调用中。

于 2020-12-30T16:02:42.307 回答
0

你从你那里得到的参考ViewChild实际上不是ElementRef。您可以将按钮包装到 adiv然后获取ViewChild对其的引用。

于 2020-12-14T08:14:23.943 回答