如何在 angular 中关闭子项的父对话框?

How to close parent dialog from child in angular?

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

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

您只需将父对话框的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();
  }
}

以我为例:

Parent:

const dialogRef = this.dialog.open(AssignResourcePageComponent);
    dialogRef.componentInstance.modal_principal_parent.on('CLOSE_PARENT_MODAL',()=>{
      dialogRef.close();
    });

Child

@Output() public modal_principal_parent = new EventEmitter();

在关闭方法中:

this.modal_principal_parent.emit('CLOSE_PARENT_MODAL');