Я работаю над входным компонентом Angular 8 OTP, где пользователи вводят 6-значный код. Поля ввода OTP динамически генерируются с использованием *ngfor, и я использую [значение] привязки и слушателей событий для обновления состояния компонента. Тем не менее, я сталкиваюсь с двумя проблемами:
- Duplication :
(индекс 1). < /li>
< /ul>
backspace поведение < /strong>: < /li>
< /ol>
Когда я нажимаю на второй ввод и нажимаю Backspace, значение при первом входе удаляется вместо второго. < /li>
< /ul>
код моего компонента
html (otp-nput.component.html): < /strong> < /p>
Код: Выделить всё
Код: Выделить всё
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();
}
}
const otpValue: string = this.otpArray.join('');
if (otpValue.length === this.otpLength) {
this.otpCompleted.emit(otpValue);
}
< /code>
}
}
ожидаемое поведение: < /strong> < /p>
Каждый Цифр должна быть введена только в выбранное поле ввода, не затрагивая других. > < /ol>
Что я пробовал: < /strong> < /p>
Заменил [значение] на [(ngmodel )
[*] Забил для неожиданных обновлений обнаружения изменений.
[*] Я добавил журналы консоли и проверил обновления в ожидаемом порядке. br /> Вручную обрабатывать обновления состояния в функции OniNput < /li>
< /ol>
Вопросы < /strong> < /p>
Почему значение дублируется в следующем поле ввода при печати? /li>
< /ol>
Подробнее здесь: https://stackoverflow.com/questions/793 ... elds-issue
Мобильная версия