Search code examples
javascriptangularpopup

How to close parent popup when closing child popup?


I'm working on a web application in Angular where I need to handle nested popups. Specifically, I have a situation where I open a popup (Popup 1) and from within that popup, I open another popup (Popup 2) when clicking on delete. What I want to achieve is that when I click "Yes" on Popup 2, both Popup 1 and Popup 2 should be closed.

Here is a full demo of my code:

Demo@StackBlitz


Solution

  • Thanks for the stackblitz. We have a method called closeAll, we can use this to close both popups.

    import { Injectable } from '@angular/core';
    import { MatDialog } from '@angular/material/dialog';
    import { CofirmDialogComponent } from '../cofirm-dialog/cofirm-dialog.component';
    import { filter } from 'rxjs';
    
    @Injectable({
      providedIn: 'root',
    })
    export class DialogService {
      constructor(private dialog: MatDialog) {}
      public deleteTaskDialog(id: number) {
        this.dialog
          .open(CofirmDialogComponent, {})
          .afterClosed()
          .pipe(filter((id) => id))
          .subscribe((confirm) => {
            this.dialog.closeAll(); // <- changed here!
          });
      }
    }
    

    Stackblitz Demo