如何从子级角度关闭父级对话框?

问题描述 投票:0回答:1

我有一个父对话框,其中有一个子对话框。在子对话框中,有一个关闭按钮。

单击此关闭按钮时,我要同时关闭父级和子级对话框。我们如何在angular6中做到这一点?

angular6 angular-material-5
1个回答
1
投票

您只需将“父”对话框的MatDialogRef传递给对话框数据中的子对话框组件,并在子组件代码中将其关闭。请找到下面的代码

  1. 这是“父组件”对话框的代码,它将打开“子”对话框并将父MatDialogRef发送到“数据”中的子对话框组件:

@Component({
  selector: 'confirmation-dialog',
  templateUrl: 'confirmation-dialog.html',
})
export class ConfirmationDialog {
  childDilogRef = null;
  message: string = "Are you sure?"
  confirmButtonText = "Yes"
  cancelButtonText = "Cancel"
  constructor(
    public dialog: MatDialog,
    @Inject(MAT_DIALOG_DATA) private data: any,
    private parentDilogRef: MatDialogRef<ConfirmationDialog>) {
      if(data){
    this.message = data.message || this.message;
    if (data.buttonText) {
      this.confirmButtonText = data.buttonText.ok || this.confirmButtonText;
      this.cancelButtonText = data.buttonText.cancel || this.cancelButtonText;
    }
      }

  }

  onConfirmClick(): void {
    this.parentDilogRef.close(true);
  }

// this method is used for opening child dialog   
OpenChild(){
     if (this.childDilogRef === null) {
        this.childDilogRef = this.dialog.open(MyChildComponent, {
          data: this.parentDilogRef, // parent dialog sent as data to child dialog component
        });
        this.childDilogRef.afterClosed().subscribe(result => {
          this.childDilogRef = null;
        });
      }
  }

}
  1. 这是子组件的代码,它将提供的ParentDialogRef初始化为本地dialogRef变量。并在单击子对话框上的按钮时关闭两个对话框引用。


@Component({
  selector: "child-dialog",
  template: `<mat-dialog-content>
    <p>
        Click on button to close both dialogs
    </p>
</mat-dialog-content>
<mat-dialog-actions align="center">
<button (click)="closeBoth()">close both dialogs</button>
</mat-dialog-actions>`,
})
export class MyChildComponent {
  constructor(
    public childDialogRef: MatDialogRef<MyChildComponent>,
    public parentDialogRef : MatDialogRef<ConfirmationDialog>,
    @Inject(MAT_DIALOG_DATA) public data: MatDialogRef<ConfirmationDialog>
  ) { 
    if(data){
      this.parentDialogRef = data
    }
  }

  // close the about dialog
  onNoClick(): void {
    this.childDialogRef.close();
  }

  closeBoth():void{
    this.childDialogRef.close();
    this.parentDialogRef.close();
  }
}

© www.soinside.com 2019 - 2024. All rights reserved.