我在Angular 1.x上找到了一些项目,用户可以通过按Enter键将焦点移至下一个控件。

'use strict';
app.directive('setTabEnter', function () {

    var includeTags = ['INPUT', 'SELECT'];

    function link(scope, element, attrs) {
        element.on('keydown', function (e) {
            if (e.keyCode == 13 && includeTags.indexOf(e.target.tagName) != -1) {
                var focusable = element[0].querySelectorAll('input,select,button,textarea');
                var currentIndex = Array.prototype.indexOf.call(focusable, e.target)
                var nextIndex = currentIndex == focusable.length - 1 ? 0 : currentIndex + 1;

                if (nextIndex >= 0 && nextIndex < focusable.length)
                    focusable[nextIndex].focus();

                return false;
            }
        });
    }

    return {
        restrict: 'A',
        link: link
    };
});

但这不适用于Angular2。如何在Angular 2中将焦点设置在Enter键上的下一个控件上?

最佳答案

import { Directive, ElementRef, HostListener, Input } from'@angular/core';
@Directive({
    selector: '[onReturn]'
})
export class OnReturnDirective {
    private el: ElementRef;
    @Input() onReturn: string;
    constructor(private _el: ElementRef) {
        this.el = this._el;
    }
    @HostListener('keydown', ['$event']) onKeyDown(e) {
        if ((e.which == 13 || e.keyCode == 13)) {
            e.preventDefault();
            if (e.srcElement.nextElementSibling) {
                e.srcElement.nextElementSibling.focus();
            }
            else{
                console.log('close keyboard');
            }
            return;
        }

    }

}

希望对您有帮助!

09-16 12:01