Angular CDK Overlay,更改默认覆盖容器

vli*_*o20 8 javascript angular-material angular angular-cdk

有没有办法改变 OverlayContainer?

我创建了一个工具提示组件,但有时我想将叠加层附加到特定元素(默认情况下,叠加层附加到文档正文)。

这是我创建叠加层的方式:

  private initOverlay(): void {
    const positionStrategy = this.overlayPositionBuilder
      .flexibleConnectedTo(this.elementRef)
      .withPositions([this.resolvedConfig]);

    this.overlayRef = this.overlay.create({positionStrategy});
  }
Run Code Online (Sandbox Code Playgroud)

这就是我将模板附加到它的方式:

  show(): void {
    this.overlayRef.attach(new TemplatePortal(this.tpl, this.viewContainerRef));
  }
Run Code Online (Sandbox Code Playgroud)

Mar*_*hal 11

请参考此 stackblitz 示例。

看起来您可以通过以下方式扩展OverlayContainer类来完成此操作 app.module.ts

{ provide: OverlayContainer, useFactory: () => new AppOverlayContainer() }

闪电战

https://stackblitz.com/edit/angular-material2-issue-ansnt5?file=app%2Fapp.module.ts


此 GitHub 评论还提供了一个示例,说明如何将其打包到 directive

GitHub 评论

https://github.com/angular/material2/issues/7349#issuecomment-337513040


修订 3/22/19 工作指令示例

OverlayContainer通过扩展类cdk-overlay-container.ts

存根类 app.module.ts

  providers: [
    { provide: OverlayContainer, useClass: CdkOverlayContainer },
  ]
Run Code Online (Sandbox Code Playgroud)

在你的cdk-overlay-container.ts你防止默认_createContainer()的工作,并提供自己的自定义的公共方法myCreateContainer来取代它。

您实际上是div在此处创建一个空的,向其中添加一个自定义类并将其my-custom-overlay-container-class附加到附加到 div的指令,然后将该容器传递给_containerElementtrue 中的私有变量OverlayContainer 类中。

/**
* Create overlay container and append to ElementRef from directive
*/ 
public myCreateContainer(element: HTMLElement): void {
   let container = document.createElement('div');
   container.classList.add('my-custom-overlay-container-class');

   element.appendChild(container);
   this._containerElement = container;
 }
 /**
  * Prevent creation of the HTML element, use custom method above
  */
 protected _createContainer(): void {
     return;
 }
Run Code Online (Sandbox Code Playgroud)

然后在你cdk-overlay-container.directive.ts的呼唤中myCreateContainer()并将其ElementRef作为参数传递。

 this.cdkOverlayContainer['myCreateContainer'](this.elementReference.nativeElement);
Run Code Online (Sandbox Code Playgroud)

然后在您的 HTML 中分配您希望它显示的指令。

<div myCdkOverlayContainer 
Run Code Online (Sandbox Code Playgroud)

闪电战

https://stackblitz.com/edit/angular-material2-issue-6nzwws?embed=1&file=app/app.component.html