1

How to focus on input field after navigating back from a child page?

Child Page

onNavigateBtnClick: function() {
    var oHistory = History.getInstance();
    var sPreviousHash = oHistory.getPreviousHash();
    if (sPreviousHash !== undefined) {
        history.go(-1);
    } else {
        var bReplace = true;
        this.getRouter().navTo("HomePage", {}, bReplace);
    }
},

Parent Page

onAfterRendering: function() {
    jQuery.sap.delayedCall(500, this, function() {
        this.getView().byId("InputField").focus();
    });
},

Problem

  1. When the nav back button is clicked first time, the onAfterRendering hook is called.
  2. If I do some action on child page then click on the nav back button, the onAfterRendering method would not be called.
Boghyon Hoffmann
  • 17,103
  • 12
  • 72
  • 170
L.Alexander
  • 23
  • 1
  • 4
  • Does this answer your question? [How to Set Initial Focus in a View?](https://stackoverflow.com/questions/36376599/how-to-set-initial-focus-in-a-view) – Boghyon Hoffmann Jul 12 '21 at 16:03

1 Answers1

0

Three steps to solve this:

Update your <App> tag of the view to have autoFocus="false". This will prevent UI5 from autofocusing the first input of the view.

In your controller's onInit, attach a method to the route that will fire when the view is navigated to, like this:

onInit: function(){
    var router = sap.ui.core.UIComponent.getRouterFor(this);

    router.getRoute("routeTargetName").attachPatternMatched(this.onNavTo, this);
}

Declare the onNavTo method in your controller that will set the focus of your input:

onNavTo: function(route){
    this.byId("MyInputField").focus();
}

Now whenever you use your router to navTo("routeTargetName"), the onNavTo method will fire, which will set focus on the field.

Paul Wieland
  • 765
  • 2
  • 10
  • 29