angular9candeactivate

Angular 9, How to return the value to canDeactivate from NgbModal return value


Thank you for helping beforehand. Im trying to use canDeactivate function with NgbModal. Which means, I want to return the value depends on NgbModal's return.

I already saw its working with comfirm alert, but Its not working as I wanted with NgbModal. Here is my code, The console.log(rtn) print "Undefined". Which I understand why, but dont know how to connect NgbModal to canDeactive(). Help me plz!

  public canDeactivate() { 
    //return confirm("Do you really want to leave?")
    const rtn = this.ExistFromExamModal(this.exitFromExamMd)
    console.log(rtn)
    return rtn
  }

  public ExistFromExamModal(content: any): any {
    this.modalService
      .open(content, {
        centered: true,
        scrollable: true,
        windowClass: 'final-confirm',
      })
      .result.then((result) => {
        if (result === 'yes') {
          return true
        } else {
          return false
        }
      })
  }

Solution

  • You will need to return an observable

      public canDeactivate() { 
        return from(
          this.modalService
            .open(this.exitFromExamMd, {
              centered: true,
              scrollable: true,
              windowClass: 'final-confirm',
            }).result
        ).pipe(
          map(result => result === 'yes')
        );
      }
    

    from turns the promise into an observable and the map function transforms the yes|no string to a boolean.

    Edit: Actually you can just make your ExistFromExamModal function return a promise. Currently it returns nothing but if you return before this.modalService it will return a promise.