Я работаю над компонентом ввода OTP Angular 8, где пользователи вводят 6-значный код. Поля ввода OTP динамически генерируются с использованием *ngFor, и я использую привязку [value] и прослушиватели событий для обновления состояния компонента. Однако я столкнулся с двумя проблемами:
- Дублирование значений:
- Когда я ввожу число в первом поле ввода (индекс 0), то же самое число появляется во втором
вводе (индекс 1).- Backspace Поведение:
- Когда я нажимаю второй ввод и нажимаю клавишу Backspace, значение в первом вводе равно удален вместо второго.
HTML (otp-input.comComponent.html):typescript (otp-nput.component.ts): [/b]Код: Выделить всё
Код: Выделить всё
import { Component, EventEmitter, Output, ViewChildren, ElementRef, QueryList } from '@angular/core'; @Component({ selector: 'app-otp-input', templateUrl: './otp-input.component.html', styleUrls: ['./otp-input.component.css'] }) export class OtpInputComponent { otpLength = 6; otpArray: string[] = new Array(this.otpLength).fill(''); @Output() otpCompleted = new EventEmitter(); @ViewChildren('otpInput') otpInputs!: QueryList; onInput(event: Event, index: number): void { const inputElement = event.target as HTMLInputElement; const value = inputElement.value; // Ensure the correct value is assigned to the correct index this.otpArray[index] = value; console.log(`User entered value "${this.otpArray[index]}" at index ${index}`); const inputEvent = event as InputEvent; if (inputEvent.inputType === 'deleteContentBackward') { console.log('User pressed delete on input ' + index); return; } if (value && index < this.otpLength - 1) { this.otpInputs.toArray()[index + 1].nativeElement.focus(); } this.checkOtpCompletion(); } onKeyDown(event: KeyboardEvent, index: number): void { if (event.key === 'Backspace') { if (this.otpArray[index]) { this.otpArray[index] = ''; // Clear current input } else if (index > 0) { console.log('Backspace pressed, moving to previous index:', index); this.otpInputs.toArray()[index - 1].nativeElement.focus(); } }}Код: Выделить всё
checkOtpCompletion(): void { const otpValue: string = this.otpArray.join(''); if (otpValue.length === this.otpLength) { this.otpCompleted.emit(otpValue); }
}
Ожидаемое поведение:- Каждый цифру следует вводить только в выбранное поле ввода, не затрагивая другие поля.
- Нажатие Backspace должно сначала очистить текущее поле, а затем переместить фокус на предыдущее поле ввода.
Что у меня есть Пробовал:- Заменил [value] на [(ngModel)
- проверил на предмет неожиданных обновлений обнаружения изменений .
- Я добавил журналы консоли и проверил, что обновления происходят в ожидаемом порядке.
- Обработка обновлений состояния вручную в функции onInput
- Почему значение дублируется в следующем поле ввода при вводе?
- Как предотвратить удаление с помощью Backspace значения предыдущего поля перед текущий?
Подробнее здесь: https://stackoverflow.com/questions/793 ... elds-issue