简体   繁体   中英

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

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/

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();
        });
    }
}));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM