angular - 如何使用 matDialog Close 而不是父对话框关闭子/嵌套对话框

标签 angular angular-material

我有两个具有某种父子关系的对话。 Parent 是一个独立的对话框组件,而 child 是从 ng-template

创建的

现在的问题是,如果我在 ng-template 中使用 matDialogClose 父对话框关闭,子对话框完好无损。

这是给你的 stackblitz https://stackblitz.com/edit/mat-dialog-example-vbxhc3

主对话框模板

<ng-template #nested>
    hey, i am nested dialog, close me with the button
    <button matDialogClose="someResult">CLOSE ME </button>
</ng-template>

打开子模板

  @ViewChild("nested")
  nestedTmplateRef;
  private dialog:MatDialog
  ...
   this.dialog.open(this.nestedTmplateRef);

我可以使用 matCloseDialog 指令关闭子对话框吗?我有兴趣使用此解决方案,因为我知道其他明显的解决方法,例如从组件控制子对话框。但是,仅使用指令可以为我节省一些样板代码。我对棱 Angular Material 组件有点生疏,可能我没有看到明显的解决方案。

最佳答案

这似乎是 Material 中的错误。如果您检查代码 here可以看到评论:

When this directive is included in a dialog via TemplateRef (rather than being in a Component), the DialogRef isn't available via injection because embedded views cannot be given a custom injector. Instead, we look up the DialogRef by ID. This must occur in onInit, as the ID binding for the dialog container won't be resolved at constructor time.

但是,当使用嵌套对话框时,getClosestDialog 方法似乎无法获取正确的对话框。

虽然我已经为它制定了一种解决方法,也许您可​​以根据此逻辑创建自定义指令以使其可重用:

通过在 MatDialogClose 上添加引用并在您的组件中查询它,您可以设置正确的对话框引用:

<ng-template #nested>
  hey, i am nested dialog, close me with the button
  <button matDialogClose="someResult" #innerClose="matDialogClose">CLOSE ME </button>
</ng-template>
@ViewChild("nested")
nestedTmplateRef;

@ViewChild('innerClose')
close: MatDialogClose;

ngOnInit(){
  const ref = this.dialog.open(this.nestedTmplateRef);  

  // have to wait for the next tick so the `dialogRef` does not get overwritten again
  setTimeout(() => this.close.dialogRef = ref);
}

working stackblitz

关于angular - 如何使用 matDialog Close 而不是父对话框关闭子/嵌套对话框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62167371/

相关文章:

javascript - NGXS:将操作分离到单独的文件中

angular - 如何获取 angular2 中的 stateparams 值?

javascript - Angular9:构建有额外的编译步骤

angular - (单击)如果来自函数,则在 *ngFor 类型的元素上损坏

html - Angular 7 Material : Horizontally align cards

javascript - AngularJS 错误处理程序不适用于单选按钮和输入

angular - 无法解析 '@angular/material/typings/'

Angular CDK 虚拟滚动无限循环

javascript - Umask 更改 ng-minlength 的最小最大长度

css - 为什么这些卡片无法正常显示?