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();
});
}
}));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With