0

Everything is working as expected, except for when the user selects "Yes, Leave" button on modal window. After clicking the "Yes, Leave" button, it closes modal window and does not navigate away to the new page.

can-deactivate-guard.service.ts

export interface CanComponentDeactivate {
    canDeactivate: () => Observable<boolean> | Promise<boolean> | boolean;
}

@Injectable()
export class CanDeactivateGuard implements CanDeactivate<CanComponentDeactivate> {
    constructor(private dialog: MatDialog) {}

    public canDeactivate(component: CanComponentDeactivate, route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    return component.canDeactivate ? component.canDeactivate() : true;
    }
}

confirm-leave-modal.component.ts

export class ConfirmLeaveModalComponent implements OnInit {
  public subject: Subject<boolean>;

  constructor(private dialog: MatDialog) { }

  public ngOnInit(): void {}

  public action(value: boolean): void {
    this.dialog.closeAll();
    this.subject.next(value);
    this.subject.complete();
  }
}

confirm-leave-modal.component.html

<div class="confirm-leave-modal">
  <header class="modal-header">
    <h2 class="modal-header__title">Unsaved Changes</h2>
  </header>
  <div class="modal-content">
    <p class="modal-content__msg">You have unsaved changes. Do you want to leave?</p>
  </div>
  <div class="modal-actions">
    <button class="modal-actions__btn" (click)="action(false)">Cancel</button>
    <button class="modal-actions__btn" (click)="action(true)">Yes, Leave</button>
  </div>
</div>

partner-information.component.ts

public canDeactivate(): Observable<boolean> | boolean {
    const editFormHasChanges: boolean = !!this.partnerContactInfoEditForm && this.partnerContactInfoEditForm.partnerFormChanged;
    const subject = new Subject<boolean>();

    if (editFormHasChanges) {
        const dialogRef = this.dialog.open(ConfirmLeaveModalComponent, { width: '450px' });
        dialogRef.componentInstance.subject = subject;

  subject.subscribe(status => {
    const isLeaving: boolean = status.valueOf();

    return isLeaving ? true : false;
  });
    } else {
        return true;
    }
}
Jason Spence
  • 472
  • 5
  • 16

0 Answers0