Open NgbModal within a Promise will not autofocus within the new modal

819 Views Asked by At

To show an error message, I want to open a modal within a Promise that gets resolved from another modal. The scenario is like this:

  1. When user clicks on a button, a modal pops up and shows a form.
  2. After user has entered the necessary information, the modal is closed and the information of user input is checked.
  3. If the input is okay, the view updates; otherwise another modal (the error modal) is opened. The user should be able to close the error modal simply by pressing the "enter" key.

Opening the error modal usually focuses on the close button. However, when I open the modal within a promise of another modal, the auto-focus does not function. This results in the weird behaviour that when user presses the "enter" key, the app executes 1 again and opens the input modal again -- without closing the error modal.

Here is the code for handling the modals:

openForm() {
    this.ngbModal.open(FormModalComponent).then(
      (success) => {
        const inputIsOkay = checkInput(success);
        if (inputIsOkay) {
          // Updating the view
        } else {
          this.ngbModal.open(ErrorModalComponent);
        }
      },
      (cancel) => {}
    );
  }

We have tried several methods to fix this behaviour:

  1. Use NgZone: instead of simply open the modal, we encapsulate the opening within a ngZone.run(). This does not change the autofocus behaviour. this.ngZone.run(()=>this.ngbModal.open(ErrorModalComponent)) does not focus on the button of the error modal.
  2. Use ChangeDetectorRef: The ngOnChanges() method of the error modal component did not fire.
  3. Use ngbAutofocus directive on the button of the error modal: This does not set the focus to the button.
  4. Use setTimeout(): We encapsulate the opening of the modal within a setTimeout() method. setTimeout(()=>this.ngbModal.open(ErrorModalComponent)); Now the autofocus functions. However, this does not feel right.

My question: What is the correct and "ng-bootstrap" way of dealing with the autofocus issue?

0

There are 0 best solutions below