0

problem faced when implement angular 4 material dialog box in candeactive

Whenever i navigate from one page to another if any changes in form field, i need to indicate "There is unsaved data.Do you want to close". This should come up with confirmation window with OK and cancel button.

On click of OK, it should navigate to other page else it must be in same page. I have tried with candeactive, it is perfectly working when I use window.confirm

 return window.confirm('There is unsaved data.Do you want to close?').

But My requirement is to implement the confirm window using Angular material dialog box. https://material.angular.io/components/dialog/overview

The problem is before retrieved the result from afterClosd. it returned false.So whenever i clicks OK or Cancel in dialog box, it didn't move to another screen.

openDialog(): boolean {
    let dialogRef = this.dialog.open(DialogOverviewExampleDialog, {
      width: '500px'

    });

    dialogRef.afterClosed().subscribe(result => {           
      if (result){
         return true;
      }else{
        return false;
      } 
    });
   return false;

  }
vik
  • 105
  • 13

1 Answers1

0

I assume you didn't see this part in the documentation ?

<button mat-button mat-dialog-close>Cancel</button>
<button mat-button [mat-dialog-close]="true">Leave</button>

Also, you should remove your last return false statement :

dialogRef.afterClosed().subscribe(result => {           
  if (result){
     return true;
  }else{
    return false;
  } 
});
// return false;

The modal is asynchronous as you can see with subscribe : this means that you are waiting for an user intercation before returning something.

In your case, you return false before the user action.

  • Hi.. Here my method openDialog() must return boolean value. so if i comment that line "return false", It will throw me an error. Problem is it returned that false without waiting for afterClosed() method. So is there are any workaround or any other way to achieve using angular dialog with dirty change when navigate to other screen. – vik Jan 22 '18 at 09:30
  • 1
    Just `return dialogRef.afterClosed()` should work. `CanDeactivate` inteface can return a boolean, a promise of a boolean, or an observable of a boolean. –  Jan 22 '18 at 09:35
  • I have tried that approach. it is not working. same problem – vik Jan 22 '18 at 09:51
  • Strange, because **[it works for me](https://stackblitz.com/edit/angular-material-1mhvrj?file=app/change/change.component.ts)**. Are you sure you correctly implemented your guard ? –  Jan 22 '18 at 10:09
  • I think canDeactive is working fine. Problem in angular material dialog only.Before the dialog box opens, the value is returned. So only it is not navigating to other screen. – vik Jan 22 '18 at 12:06
  • And that's exactly what I told you to do : remove the last `return false` from your code and directly return the `afterClosed` result. –  Jan 22 '18 at 12:12