可以使用Angular的指令来实现自动聚焦下一个输入框达到最大长度的功能。以下是一个示例的解决方法:
import { Directive, ElementRef, HostListener } from '@angular/core';
@Directive({
selector: '[appAutoFocusNext]'
})
export class AutoFocusNextDirective {
constructor(private el: ElementRef) {}
@HostListener('input', ['$event.target'])
onInput(target: HTMLInputElement) {
const maxLength = target.getAttribute('maxlength');
const currentLength = target.value.length;
if (currentLength >= parseInt(maxLength)) {
const nextInput = target.nextElementSibling as HTMLInputElement;
if (nextInput) {
nextInput.focus();
}
}
}
}
import { NgModule } from '@angular/core';
import { AutoFocusNextDirective } from './auto-focus-next.directive';
@NgModule({
declarations: [
AutoFocusNextDirective
],
exports: [
AutoFocusNextDirective
]
})
export class AppModule { }
这样,当一个输入框的文本长度达到最大长度时,焦点会自动切换到下一个输入框。注意要在每个输入框上设置maxlength属性,该属性表示输入框的最大长度。