Angular 自定义元素 & Angular 8 Material:MatDialog 和 MatMenu 不工作

Angular Custom Elements & Angular 8 Material: MatDialog and MatMenu not working

我正在使用 angular 自定义元素构建一个应用程序,其中 MatDialog 是自定义元素的一部分。我在主机应用程序中也有一个 MatMenu。问题是,当我在页面加载时打开 mat-dialog 然后打开 mat-menu 时,mat-dialog 之后不起作用,否则如果我先打开菜单然后再打开 mat-dialog,则菜单不起作用工作了。

您可以在以下位置找到 stackblitz:https://stackblitz.com/edit/angular-nr58ab-tbu38h

我在 index.html 本身中添加了 MatDialog 应用程序的 main.js 代码。 main.js 是在生产模式下使用 ngx-build-plus 构建应用程序后生成的,输出散列 none 和单包为真。

MatDialog应用代码如下:

app.module.ts

import { BrowserModule } from "@angular/platform-browser";
import { BrowserAnimationsModule } from "@angular/platform-browser/animations";

import { NgModule, Injector } from "@angular/core";

import { AppRoutingModule } from "./app-routing.module";
import { AppComponent } from "./app.component";
import { createCustomElement } from "@angular/elements";

import { MatDialogModule, MatButtonModule } from "@angular/material";


@NgModule({
  declarations: [AppComponent],
  imports: [
    BrowserModule,
    AppRoutingModule,
    MatDialogModule,
    BrowserAnimationsModule,
    MatButtonModule
  ],
  providers: [],
  bootstrap: [AppComponent],
  entryComponents: [AppComponent]
})
export class AppModule {
  constructor(private injector: Injector) {
    const myCustomElement = createCustomElement(AppComponent, {
      injector: this.injector
    });
    customElements.define("app-test-data", myCustomElement);
  }
  ngDoBootstrap() {}
}

app.component.ts

import { Component, Input, TemplateRef } from "@angular/core";
import { MatDialog } from "@angular/material";

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  constructor(private dialog: MatDialog) {}
  openModal(temp: TemplateRef<any>) {
    this.dialog.open(temp, { width: "100px", height: "100px" });
  }
}

和app.component.html

<button mat-raised-button (click)="openModal(modal)">Open</button>

<ng-template #modal>
  <mat-dialog-content>
    Hello
  </mat-dialog-content>
</ng-template>

这是我构建并放入 stackblitz 应用程序 index.html 中的应用程序。

我坚持这个有一段时间了,我也试过 运行 NgZone.run() 里面的 dialog.open() ,但也没有运气。谢谢。

更改自定义元素的名称

customElements.define("app-custom-component", myCustomElement);

Working Demo

在此演示中运行良好。

如果您仍然遇到问题,请告诉我。

如果您使用的是 Angular 版本 8 及以下。考虑升级到 angular 10.

我们也面临与 angular 基于元素的微前端相同的问题。将应用程序升级到 angular 10,问题神奇地解决了。 :)