angularjsangular-materialmd-autocomplete

how set focus in angular md-autocomplete?


I have a dialog with few field to set, the first field is a md-autocomplete, when I click ok all these fields are cleaned, so, I want set focus true in the md-autocomplete, for starting to filling data again.


Solution

  • Try this :

    JS:

    $scope.setFocus = function() {
      setTimeout(function() {
        document.querySelector('#autoCompleteId').focus();
      }, 0);
    }
    

    HTML:

    <md-autocomplete .............. md-input-id="autoCompleteId">
      <!-- Note the id -->
    </md-autocomplete>
    
    <input type="button" value="clickMeForFocus" ng-click="setFocus()" />
    

    The timeout is needed to make sure that the autocomplete component is rendered at the time of calling focus.