maxlength reach focus on next input angular code example
Example 1: maxlength reach focus on next input angular
<form class="digit-group" #userForm="ngForm" (ngSubmit)="onSubmit(userForm.value)" ngNativeValidate>
<input type="text" maxlength="1" id="digit-1" name="digit-1" />
<input type="text" maxlength="1" id="digit-2" name="digit-2" />
<input type="text" maxlength="1" id="digit-3" name="digit-3" />
<!-- <span class="splitter">–</span> -->
<input type="text" maxlength="1" id="digit-4" name="digit-4" />
<input type="text" maxlength="1" id="digit-5" name="digit-5" />
<input type="text" maxlength="1" id="digit-6" name="digit-6" />
<div class="row">
<div class="col px-0 pt-4 pb-2 text-center">
<button type="button" class="btn btn-warning" (click)="dismissModal()">Close</button>
<button type="submit" class="btn btn-success">Submit</button>
</div>
</div>
</form>
ngOnInit(): void {
var container = <HTMLInputElement>document.getElementsByClassName("digit-group")[0];
container.onkeyup = function (e) {
var target = <HTMLInputElement>e.target;
var maxLength = parseInt(target.attributes["maxlength"].value, 10);
var myLength = target.value.length;
if (myLength >= maxLength) {
var next = target;
while (next = <HTMLInputElement>next.nextElementSibling) {
if (next == null)
break;
if (next.tagName.toLowerCase() === "input") {
next.focus();
break;
}
}
}
}
}
Example 2: change the focus to next in angular forms
import { Directive, ElementRef, HostListener, Input } from '@angular/core';
@Directive({
selector: '[moveNextByMaxLength]'
})
export class MoveNextByMaxLengthDirective {
constructor(private _el: ElementRef) { }
@HostListener('keyup', ['$event']) onKeyDown(e: any) {
if (e.srcElement.maxLength === e.srcElement.value.length) {
e.preventDefault();
let nextControl: any = e.srcElement.nextElementSibling;
while (true)
{
if (nextControl)
{
if (nextControl.type === e.srcElement.type)
{
nextControl.focus();
return;
}
else
{
nextControl = nextControl.nextElementSibling;
}
}
else
{
return;
}
}
}
}
}