【问题标题】:Angular CDK Overlay flexibleConnectedTo doesn't connect to originAngular CDK Overlay flexibleConnectedTo 未连接到原点
【发布时间】:2020-04-28 11:42:55
【问题描述】:

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

覆盖按钮.html:

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

overlay-button.component

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

  constructor(private _overlay: OverlayService) {}

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

overlay.service

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未定义或类似的东西,但事实并非如此。我尝试了使用类似代码找到的每个教程,但没有任何效果。问题可能出在其他地方吗?

下面是它的说明:

【问题讨论】:

  • 嘿 Yannick,我遇到了完全相同的问题,并且也确认不是因为未定义/空参考。你设法解决了这个问题吗?

标签: angular-material angular-cdk


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-06-16
      • 1970-01-01
      • 2020-12-07
      • 2019-04-08
      • 1970-01-01
      • 1970-01-01
      • 2020-06-20
      相关资源
      最近更新 更多