首页 > 解决方案 > 通过 dialogRef 更新父组件而不关闭对话框

问题描述

我有一个子对话框和一个父组件,我的父组件有一个 MataTable,在我单击子对话框上的更新后更新。

这是父级上的代码,就像一个魅力一样:

父组件.ts

 openDialog(e: any) {

    this.data = e;
    const dialogRef = this.dialog.open(DialogAddMarqueComponent, {
      data: this.data,
      restoreFocus: false,
    });

    console.log(this.dialogRef)

    dialogRef.afterClosed().subscribe((result) => {
      if (result.length !== 0) {
        this.products.data.push(result);
        this.products = new MatTableDataSource(this.products.data);
      } else { return; }
    });
  }

我添加了一个类似于更新的新功能和按钮,但没有关闭 DialogRef,所以我想实现我在dialogRef.afterClosed()中实现的目标,但不关闭按钮。

子组件.ts

this.appService.addProduct(this.product)
    .subscribe(
        response => {
            this.product = response;
            this.products.data.unshift(response);
            // this.dialog.close(response); // that will trigger the dialogRef.afterclosed()

        }, error => {
            console.warn('ERROR', error);
        }
    );

我想我需要在父端订阅 dialogRef ,只要我点击复制按钮,它就会更新父端。但是找不到要使用的 dialogRef 函数(我试过获取状态)有没有办法做到这一点?

标签: angularangular-material

解决方案


对话框不支持更改检测。

所以我建议你以这种方式实现这一目标:

  1. 创建服务。( ng g s <service-name>)
  2. 将变量放入该服务中,以便您可以在两个页面中引用它们。

现在,如果您在对话框中更改数据,它将在父页面中更改。


推荐阅读