Angular CDK Overlay, change default overlay container

本小妞迷上赌 提交于 2019-12-06 09:39:29

Please reference this stackblitz example.

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

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

Stackblitz

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


This GitHub comment also provides an example of how to package this in a directive

GitHub comment

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


Revision 3/22/19 working directive example

Extend the OverlayContainer class via cdk-overlay-container.ts

Stub the class in app.module.ts

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

In your cdk-overlay-container.ts you are preventing the default _createContainer() from working, and providing your own custom public method myCreateContainer to replace it.

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

Then in your cdk-overlay-container.directive.ts your are calling myCreateContainer() and passing the ElementRef as an argument.

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

Then in your HTML assign the directive where you want it to show up.

<div myCdkOverlayContainer 

Stackblitz

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!