gpt4 book ai didi

javascript - 改进管脚输入组件

转载 作者:行者123 更新时间:2023-11-30 11:06:08 24 4
gpt4 key购买 nike

我有一个包含四个只能输入数字的输入字段的组件。输入后,焦点从当前输入字段跳到下一个输入字段。删除也有效(当按下退格键时)- 删除当前字段中的值会将焦点移至上一个字段。

我遇到的问题是当前的实现是相当静态的,这意味着某些值是硬编码的。如果你看at this demo ,您会看到每个 (input) 事件都会发送一个硬编码索引。与每个 (delete) 相同。

另一个限制是,如果我想添加第五个输入,我需要复制一个现有输入并进行一些调整。

所以我的挑战是如何让它更具活力和灵 active 。就像指定应该有多少输入一样。也不要对索引进行硬编码,而是能够从代码中找出答案。

关于如何做到这一点有什么建议吗?

最佳答案

在此示例中,我使用的是响应式(Reactive)表单。我会将其作为一个单独的组件,您只需将位数传递给该组件,然后由该组件处理其他所有事情。您可能需要将数字传递给父组件,为此您可以使用 @Output。您不需要创建组件,但为了清洁起见,我会这样做:)

因此我们可以创建一个 HelloComponent(名称刚从 stackblitz 模板中获取),我们将在其中构建表单,将尽可能多的表单控件推送到您指定的数组:

@Input() numOfDigits;

@ViewChildren('inputs') inputs: QueryList<any>;

confirmCodeForm: FormGroup;

constructor(private fb: FormBuilder) {
this.confirmCodeForm = this.fb.group({
digits: this.fb.array([]) // create empty form initially
});
}

ngOnInit() {
// push form controls to the formarray
for (let i = 0; i< this.numOfDigits; i++) {
(this.confirmCodeForm.get('digits') as FormArray).push(this.fb.control(null))
}
}

然后处理事件并检查有效数字,改变对字段的关注等,这在 keydown 上触发:

check(index, field, event) {
if (isNaN(parseInt(event.key, 10)) && event.key !== 'Backspace') {
event.preventDefault();
}
else if (field.value && event.key !== 'Backspace') {
if (index < this.inputs.toArray().length - 1) {
this.inputs.toArray()[index + 1].nativeElement.focus();
}
}
else if (event.key === 'Backspace') {
if (index > 0) {
field.setValue(null)
this.inputs.toArray()[index - 1].nativeElement.focus();
} else {
console.log('first field');
}
}
}

然后在模板中我们将迭代表单数组,然后我们就完成了!

<form (ngSubmit)="confirmCode(confirmCodeForm.value)" [formGroup]="confirmCodeForm">
<div formArrayName="digits">
<input *ngFor="let field of confirmCodeForm.get('digits').controls;
let i = index"
#inputs
[maxLength]="1"
[formControlName]="i"
(keydown)="check(i, field, $event)">
</div>
</form>

没有这个组件很容易使用

<hello [numOfDigits]="4"></hello>

DEMO

关于javascript - 改进管脚输入组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55539336/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com