问题描述
是否可以更改OverlayContainer?
Is there a way to change the OverlayContainer?
我已经创建了一个工具提示组件,但有时我想将覆盖图附加到特定元素(默认情况下,覆盖图附加到文档主体).
I have created a tooltip component, but sometimes I want to attach the overlay to a specific element (by default the overlay is attached to the document body).
这是我创建叠加层的方式:
Here is how I am creating the overlay:
private initOverlay(): void {
const positionStrategy = this.overlayPositionBuilder
.flexibleConnectedTo(this.elementRef)
.withPositions([this.resolvedConfig]);
this.overlayRef = this.overlay.create({positionStrategy});
}
这是我将模板附加到它的方式:
And this is how I am attaching a template to it:
show(): void {
this.overlayRef.attach(new TemplatePortal(this.tpl, this.viewContainerRef));
}
推荐答案
请参考以下stackblitz示例.
Please reference this stackblitz example.
{ provide: OverlayContainer, useFactory: () => new AppOverlayContainer() }
Stackblitz
https://stackblitz.com/编辑/angular-material2-issue-ansnt5?file=app%2Fapp.module.ts
此GitHub注释还提供了如何将其打包到directive
This GitHub comment also provides an example of how to package this in a directive
GitHub评论
https://github.com/angular/material2/issues/7349# issuecomment-337513040
19/3/22修订版工作指令示例
通过cdk-overlay-container.ts
在app.module.ts
providers: [
{ provide: OverlayContainer, useClass: CdkOverlayContainer },
]
在您的cdk-overlay-container.ts
中,您将阻止默认的_createContainer()
工作,并提供您自己的自定义公共方法myCreateContainer
来替换它.
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.
/**
* 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
作为参数传递.
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);
然后在HTML中将指令分配到您希望其显示的位置.
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
这篇关于Angular CDK叠加层,更改默认叠加层容器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!