odran037
odran037

Reputation: 271

Angular Routes / input autofocus

I'm using angular route. Each page(route) has an input field. I have successfully used the attribute autofocus on the first page. When I navigate to the other pages, the input does not autofocus. Returning to the first page does not autofocus the input again. I understand now why it doesn't work but would like to know if there is a way to accomplish this.

I'm new to Angular and I'm not sure I understand what I read about ngFocus:

https://docs.angularjs.org/api/ng/directive/ngFocus

Upvotes: 11

Views: 2726

Answers (2)

stefku
stefku

Reputation: 117

In my case, the answer of Travis Collins did not work because somehow, the element was an array of inputs.

So I have to use the slightly modified version. Note, with arrow functions.

.directive('autofocus', ($timeout) => ({
    link: (scope, element: any, attrs) => {
        if (!element.focus && element.length) {
            element = element[0];
        }
        $timeout(() => {
            element.focus();
        });
    }
}));

Upvotes: 1

Travis Collins
Travis Collins

Reputation: 4010

ngFocus is not what you're looking for. That directive is more of an event trigger. It will execute your code whenever the user gives focus to the textbox.

What you want is something like this custom directive:

angular
    .module('myApp')
    .directive('autofocus', function($timeout) {
        return {
            link: function(scope, element, attrs) {
                $timeout(function() {
                    element.focus();
                });
            }
        }
    });

Inspired by http://ericclemmons.com/angular/angular-autofocus-directive/

Upvotes: 9

Related Questions