【问题标题】:Angular 9 Material Dialog returning undefined on closeAngular 9 Material Dialog在关闭时返回未定义
【发布时间】:2020-09-19 19:50:49
【问题描述】:

我正在使用 Angular 9,并且有一个 Material 对话框,设置为在关闭时返回 "test",如下所示:

<mat-dialog-actions align='center'>
    <button mat-raised-button color='primary' [mat-dialog-close]='"test"'>
        Submit
    </button>
</mat-dialog-actions>

在我的主页组件中,我订阅了 afterAllClosed:

  constructor(private matDialog: MatDialog) { }

  OpenMatDialog(data): void {
    this.matDialog.open(
      DialogComponent,
      { data },
    );

    if( !this.matDialogCloseSub$ )
      this.matDialogCloseSub$ = this.matDialog.afterAllClosed.subscribe(result => {
        console.log(result);
      });
  }

但是,result 总是以 undefined 的形式返回。我做错了什么?

我在entrycomponents中设置了app.module.ts中的对话框组件如下:

@NgModule({
  declarations: [
    AppComponent,
    DialogComponent
  ],
  imports: [
    MatDialogModule,
  ],
  entryComponents: [
    DialogComponent,
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

【问题讨论】:

    标签: angular angular-material


    【解决方案1】:

    Observable afterAllClosed 不返回任何值,因为它不知道应该返回哪个对话框数据。您应该使用来自MatDialogRefafterClosed,它是从open 调用返回的:

    OpenMatDialog(data): void {
      const dialogRef = this.matDialog.open(
        DialogComponent,
        { data },
      );
    
      if( !this.matDialogCloseSub$) {
        this.matDialogCloseSub$ = dialogRef.afterClosed.subscribe(result => {
          console.log(result);
        });
      }
    }
    

    但是,考虑到您正在使用一些自定义全局方法 OpenMatDialog,我确实看到了一些问题,但至少您现在知道如何从对话框中获取结果 :)。您将不得不使用对话引用,而不是对话服务。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-18
      • 1970-01-01
      • 1970-01-01
      • 2023-01-28
      • 2016-12-23
      • 1970-01-01
      相关资源
      最近更新 更多