简体   繁体   English

角度路径/输入自动对焦

[英]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. 我已经在第一页上成功使用了属性autofocus。 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: 我是Angular的新手,我不确定我理解我读到的关于ngFocus的内容:

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

ngFocus is not what you're looking for. ngFocus不是你想要的。 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/ 灵感来自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. 就我而言,Travis Collins的答案不起作用,因为不知何故,元素是一系列输入。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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