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

标签 javascript angular angular-material angular-cdk

有没有办法改变 OverlayContainer?

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

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

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

    this.overlayRef = this.overlay.create({positionStrategy});
  }

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

  show(): void {
    this.overlayRef.attach(new TemplatePortal(this.tpl, this.viewContainerRef));
  }

最佳答案

请引用这个 stackblitz 示例。

looks like you can accomplish this by extending the OverlayContainer class via the following in app.module.ts

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

堆栈 Blitz

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 工作指令示例

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

app.module.ts 中 stub 类

  providers: [
    { provide: OverlayContainer, useClass: CdkOverlayContainer },
  ]

在您的 cdk-overlay-container.ts 中,您正在阻止默认的 _createContainer() 工作,并提供您自己的自定义公共(public)方法 myCreateContainer 来替换它。

You are essentially creating an empty div here, adding a custom class to it my-custom-overlay-container-class and appending it to the div the directive is attached to, then passing that container to the private variable _containerElement in the true OverlayContainer class.

/**
* 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;
 }

然后在您的 cdk-overlay-container.directive.ts 中调用 myCreateContainer() 并将 ElementRef 作为参数传递。

 this.cdkOverlayContainer['myCreateContainer'](this.elementReference.nativeElement);

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

<div myCdkOverlayContainer 

堆栈 Blitz

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

关于javascript - Angular CDK Overlay,更改默认覆盖容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55288559/

相关文章:

javascript - NodeJS(Firebase): Cannot import custom class

angular - Material snackbar 可观察到的内容是否完整?

angularjs - 如何以编程方式打开 Angular md-autocomplete?

php - 推送通知如何工作?

javascript - jquery select2 如果在源中找不到,则将文本添加到源

angular - 为什么我在刚启动的 Angular2 应用程序中会收到此错误?

angular - 通过服务将参数传递给 ngOnInit

javascript - 引用错误: google is not defined After Page Refresh

angular-material - mat-form-field floatLabel ="never"不工作

javascript - (Vue, ChartJS) 从子组件 Canvas 上下文为图表创建渐变背景