在ShadowDOM中使用CDK覆盖容器



我试图在web组件中使用Angular Material组件。除了cdk覆盖的一个边缘情况外,一切都在工作。到目前为止,我已经成功地使用_createContainer()的重写将覆盖容器附加到shadowroot内部的div中,以便应用样式。然而,如果我用*ngIf隐藏父元素,然后将其切换回来,覆盖容器是存在于DOM中,但它和它所包含的元素是不可见的。

是否有我错过的东西,我需要手动清除或切换一些东西,以使该行为正常工作?

代码是基于这个答案:将MatDialog弹出框添加到Angular根,而不是body

@Injectable({ providedIn: "root" })
export class AppOverlayContainer extends OverlayContainer implements OnDestroy {
constructor(@Inject(DOCUMENT) _document: any) {
super(_document);
}
ngOnDestroy() {
super.ngOnDestroy();
}
getRootElement(): Element {
return this._document
.querySelector("web-component-tag")
.shadowRoot.querySelector("#angular-app-root");
}
createContainer(): void {
this._createContainer();
}
protected _createContainer(): void {
super._createContainer();
this._appendToRootComponent();
}
private _appendToRootComponent(): void {
if (!this._containerElement) {
return;
}
const rootElement = this.getRootElement();
const parent = rootElement || this._document.body;
parent.appendChild(this._containerElement);
}
}

HTML

<ng-container *ngIf="toggleWidget$ | async">

<app-conversations
id="angular-app-root"
[toggleWidget$]="toggleWidget$"
[contextTitle]="contexttitle"
[contexts]="contexts"
[preloadConversations]="subscribeonload"
[widgetIdentifier]="uniqueId"
></app-conversations>
</ng-container>
<ng-container
*ngIf="(toggleWidget$ | async) === false && !overridelaunchbutton"
>
<button
mat-fab
class="message-button"
color="primary"
(click)="toggleWidget$.next(true)"
>
<mat-icon svgIcon="message"></mat-icon>
<div class="unread-pip" *ngIf="hasUnreadMessages">
{{ unreadMessageCount }}
</div>
</button>
</ng-container>
<ng-container *ngIf="overridelaunchbutton">
<button
mat-icon-button
[ngClass]="launchbuttonclass"
[color]="launchbuttoncolor"
(click)="toggleWidget$.next(true)"
>
<mat-icon svgIcon="{{ launchbuttonicon }}"></mat-icon>
<div class="unread-pip" *ngIf="hasUnreadMessages">
{{ unreadMessageCount }}
</div>
</button>
</ng-container>

我从来没有发现根这超出奇怪的行为发生,如果覆盖容器是由一个*ngIf包装。当*ngIf第一次显示,切换为不可见,然后再次显示时,它会导致内容在容器内呈现的问题。在我的情况下,把它移到*ngIf之外修复了这个问题。

最新更新