如何使用 mat-dialog 的backgroundClick 关闭对话框并将更改的数据发送回父组件

Rod*_*edo 8 angular-material angular

我有以下场景:我使用 mat-dialog 来显示 *ngFor 卡的信息,在这张卡中,有一些静态信息,例如消息正文、标题和发布者,但我也有动态元素,在本例中是一个“喜欢”按钮。

当有人单击对话框外部的“喜欢”按钮(这是出版物的展开视图)时,“喜欢”按钮会变成红色,并且它的计数器收到它的值+ 1,如果该人再次单击它,它会变成灰色并具有 de 值其中 - 1。

如果有人打开对话框并单击按钮,然后单击关闭按钮,它工作正常,但如果有人单击“喜欢”按钮,然后单击背景或按“esc”,则数据不会发送回父组件。

我的代码如下:

visualize(value: any) { //method that opens the dialog

    if (value.link && !value.video_destaque)
        window.open(value.link, "_blank");
    else {
        const publicationData = { //pass the data to dialog
            id: value.id,
            cabecalho: value.header,
            corpo: value.body,
            ...
            curtiu: value.curtiu,
            classeFavorite: value.classeFavorite,
            num_curtidas: value.num_curtidas,
        };

        const dialogRef = this.dialog.open(VisualizePublicationComponent, { //open dialog
            maxHeight: '85vh',
            width: '70vh',
            panelClass: 'custom-dialog-container',
            disableClose: true,
            data: {
                publicacao: publicationData
            }
        });

        dialogRef.afterClosed().subscribe(result => { 
            this.post.curtiu = result.curtiu;
            this.post.favoritou = result.favoritou;
            this.post.num_curtidas = result.num_curtidas;
            this.post.classeLike = result.classeLike;
            this.post.classeFavorite = result.classeFavorite;
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

最后一部分“dialogRef.afterClosed...”将数据传递回父组件,但它仅适用于 mat-dialog-close 按钮​​,似乎如果您单击对话框外部,它会认为您想要取消并完全取消忘记数据。

因为它是一个“喜欢”按钮,用户可能想要阅读该帖子,然后喜欢它并以最简单的方式关闭它(在框外单击)。

我认为我的问题的答案与以下代码有关

dialogRef.backdropClick().subscribe(() => {
    dialogRef.close();
})
Run Code Online (Sandbox Code Playgroud)

但我不知道我错过了什么。

Ami*_*ian 9

尝试添加这个

可视化发布组件

...
constructor(public dialogRef: MatDialogRef<VisualizePublicationComponent>) {  }
...

ngOnInit() {
   this.dialogRef.beforeClose().subscribe(() => this.dialogRef.close(this.resultData));
}
...
Run Code Online (Sandbox Code Playgroud)

其中this.resultData是要返回给父组件的数据。我已经尝试过了,它适用于 esc 和背景点击。希望有帮助。