我在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
};
});
但这对Angular 2不起作用。如何在Angular 2中的Enter keypress上设置焦点到下一个控件?
答案 0 :(得分:10)
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;
}
}
}
希望它会对你有所帮助!
答案 1 :(得分:4)
import { Directive, ElementRef, HostListener, Input, Renderer } from '@angular/core';
@Directive({
selector: '[onReturn]'
})
export class OnReturnDirective {
private el: ElementRef;
@Input() onReturn: string;
constructor(private _el: ElementRef,public renderer: Renderer) {
this.el = this._el;
}
@HostListener('keydown', ['$event']) onKeyDown(e:any) {
if ((e.which == 13 || e.keyCode == 13)) {
e.preventDefault();
let control:any;
control = e.srcElement.nextElementSibling;
while (true){
if (control) {
if ((!control.hidden) &&
(control.nodeName == 'INPUT' ||
control.nodeName == 'SELECT' ||
control.nodeName == 'BUTTON' ||
control.nodeName == 'TEXTAREA'))
{
control.focus();
return;
}else{
control = control.nextElementSibling;
}
}
else {
console.log('close keyboard');
return;
}
}
}
}
}