I have found some project on Angular 1.x where user can move focus to next control by pressing Enter key.
'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
};
});
But this does not work for Angular 2. How can I set focus on next control on Enter keypress in Angular 2?
We can use focus() function to focus the particular input field.
FCS is a jQuery plugin that has the ability to automatically move focus on the next form field when Enter key is pressed. The main goal of the plugin is to set focus on the next input field by pressing Enter key. It also supports any type of form controls like textarea, button, select, and more.
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;
}
}
}
}
}
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