【问题标题】:Angular Material Dialog -> afterClosed -> which button was pressedAngular Material Dialog -> afterClosed -> 按下了哪个按钮
【发布时间】:2018-04-09 13:46:54
【问题描述】:

我在我的应用程序中使用 Angular Material 以及 Angular Material 对话框。 关闭对话框后,应根据单击的按钮执行操作 A 或操作 B:

dialogRef.afterClosed().subscribe(() => {
    // if close button was clicked do action A
    // if other button was clicked do action B
 })

是否有可能检测到在 afterClosed 方法中单击了哪个按钮?

【问题讨论】:

    标签: angular angular-material


    【解决方案1】:

    您可以使用自定义数据关闭对话框。像这样:

    在您的对话框组件中:

    @Component({/* ... */})
    export class YourDialog {
      constructor(public dialogRef: MatDialogRef<YourDialog>) { }
    
    
      closeA() {
        this.closeDialog('A')
      }
    
      closeB() {
        this.closeDialog('B');
      }
    
      closeDialog(button: 'A' | 'B') {
        this.dialogRef.close(button);
      }
    }
    

    像这样处理关闭:

    dialogRef.afterClosed().subscribe(result => {
      if (result === 'A') {
        // handle A button close
      }
    
      if (result === 'B')
        // handle B button close
      }
    });
    

    由于afterClosed() 是可观察的,您可以过滤此流以创建更具声明性的解决方案:

    const closedA$ = dialogRef.afterClosed().pipe(filter(result => result === 'A'));
    const closedB$ = dialogRef.afterClosed().pipe(filter(result => result === 'B'));
    
    closedA$.subscribe( // handle A);
    closedB$.subscribe( // handle B);
    

    【讨论】:

      【解决方案2】:

      我目前使用的方式是在关闭时从对话框传递一个字符串:

      this.dialogRef.close('A or B or whatever');
      

      我在外面这样使用它们:

        dialogRef.afterClosed().subscribe((result: any) => {
          if (resuld === 'A'){
            // if close button was clicked do action A
          } else if (resuld === 'B') {
            // if other button was clicked do action B
          }
       })
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-05-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-05-22
        • 1970-01-01
        相关资源
        最近更新 更多