Angular 2: use CanDeactivate, but showing modals instead of window.confirm

How can I use CanDeactivate using a bootstrap modem instead of confirmation? The point is, how can I return the observed execution of this process?

The code is as follows. CheckoutComponent is the same component, and I have a modal one and one that I want to prevent from deactivating

public modalResponse: Observable<boolean> = new Observable((observer) => { });

public saveChanges() { ///OPEN MODAL AFTER CANDEAC
    this.openSaveChangeModal();
    return this.modalResponse.take(1);
}

canDeactivate(component: CheckoutComponent){
    if(this.nav)
        return true;

    else{
        component.saveChanges(); // Opens modal
    return component.modalResponse.take(1);
    }
}

// Modal save changes
public openSaveChangeModal() {
    jQuery('#deactModal').modal();
}

public acceptNavigate(){
    this.modalResponse = new Observable((observer) => {observer.next(true); });
    jQuery('#deactModal').modal('hide');
}

public cancelNavigate(){
    this.modalResponse = new Observable((observer) => { observer.next(false); });

    jQuery('#deactModal').modal('hide');
}

But I deal with

TypeError: unable to read the "saveChanges" property from undefined

+4
source share
1 answer

, Promise Observable, . :

canDeactivate(): Promise<boolean> {

        let $modal = jQuery('#deactModal').modal();
        return new Promise<boolean>((resolve, reject) => {
          document.getElementById("btnAccept").onclick = ((e: any) => {
              jQuery('#deactModal').modal('hide');
              resolve(true);
          });

          document.getElementById("btnCancel").onclick = ((e: any) => {
              jQuery('#deactModal').modal('hide');
              resolve(false);
          });

          $modal.modal("show");

        });  
}

bootstrap angular jQuery.

+4

Source: https://habr.com/ru/post/1664140/


All Articles