Angular Dialog: How to make the button open or close depending on state

1k views Asked by At

I am using the Dialog component and I need the main button to close the dialog when the dialog is opened. I am using the dialog with no backdrop overlay because I need the user to interact with the page while the dialog is opened. The close button of the dialog works fine. I tried the @input with a new variable and I tried the getState and MatDialogState without success, I just break my button. I couldn't find any examples. Here is my code :

export class DialogButton {

  constructor(
    public dialog: MatDialog,
    public dialogRef: MatDialogRef<DialogComponent>,
    ) { }

    toggleDialog() {
          this.dialog.open(DialogComponent, {
          id: 'legend-button-dialog-container',
          disableClose: false,
          hasBackdrop: false,
          });
        }
}
2

There are 2 answers

1
Zerotwelve On BEST ANSWER

try something like this, should work

dialogRef = null;

toggleDialog() {
    if(this.dialogRed === null){
        this.dialogRef = this.dialog.open(DialogComponent, {
            id: 'legend-button-dialog-container',
            disableClose: false,
            hasBackdrop: false,
        });
    }else{
        this.dialogRef.close();
        this.dialogRef = null;
    }
}

0
snowlight On

the code above generated an issue, if we close the dialog using the close button, we needed to clic twice on the dialog button to open it. This code fixed it:

export class MyButtonComponent {

  @Input() isDialogOpened: boolean;

  constructor(
    public dialog: MatDialog
    ) { }

    dialogRef = null;

    toggleDialog() {
      const dialogOpened = this.dialog.getDialogById('my-button-dialog-container');
        if(!dialogOpened) {
            this.dialogRef = this.dialog.open(MyButtonDialogComponent, {
                id: 'my-button-dialog-container',
                hasBackdrop: false,
            });
        } else {
            this.dialogRef.close();
        }
    }
}