Я работаю над входным компонентом Angular 8 OTP, где пользователи вводят 6-значный код. Поля ввода OTP динамически генерируются с использованием *ngfor, и я использую [значение] привязки и слушателей событий для обновления состояния компонента. Тем не менее, я сталкиваюсь с двумя проблемами:
- Duplication :
(индекс 1). < /li>
< /ul>
- backspace поведение < /strong>: < /li>
< /ol>
Когда я нажимаю на второй ввод и нажимаю Backspace, значение при первом входе удаляется вместо второго. < /li>
< /ul>
код моего компонента
html (otp-nput.component.html): < /strong> < /p>TypeScript (otp-input.comComponent.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(); } } < /code> } < /p> 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