Search code examples
angulartypescriptrxjsangular-materialmat-dialog

Open several mat-dialogs one by one after the previous one is closed


In my code I have a button which will browse a list of data and open a mat-dialog for each data.

Unfortunately, during the course of the loop, all the mat-dialogs open.

What I would like to happen is that by using the dialogRef.afterClosed() method, depending on the result (true) the next mat-dialog opens or (false) the loop ends.

openDialog(): void {
  this.data.forEach(data => {
    const dialogRef = this.dialog.open(DialogOverviewExampleDialog, {
      disableClose: true
    });
    dialogRef.componentInstance.data = data;

    dialogRef.afterClosed().subscribe(result => {
      if (result) {
        // open next mat-dialog
      } else {
        // stop loop
      }
    });
  });
}

<div mat-dialog-actions>
  <button mat-button (click)="_dialogRef.close(true)">Ok</button>
  <button mat-button (click)="_dialogRef.close(false)">Cancel</button>
</div>

StackBlitz Here

How can I do this? I don't know how to go about it.

Thanks for your help.


Solution

  • You can achieve this by rxjs takeWhile

    from(this.data)
          .pipe(
            concatMap(x => {
              const dialogRef = this.dialog.open(DialogOverviewExampleDialog, {
                disableClose: true
              });
    
              dialogRef.componentInstance.data = x;
    
              return dialogRef.afterClosed();
            }),
            takeWhile(Boolean)
          ).subscribe();
    

    See https://stackblitz.com/edit/open-mat-dialogs-one-by-one-after-the-previous-one-is-cl-yqprmt?file=src/app/dialog-overview-example.ts