javascript - 改进管脚输入组件

标签 javascript angular

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

我遇到的问题是当前的实现是相当静态的,这意味着某些值是硬编码的。如果你看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/

相关文章:

javascript - 在 Angular 中循环数组时无法读取 0 undefined 的属性

javascript - 响应式表格设计: Make click() expand tr using JQuery

javascript - Angular : Controller is undefined when adding a directive

javascript - 处理 jquery Promise 时函数序列未按预期执行

javascript - 阻止事件冒泡到父级

javascript - 我可以使用 Angular 日期管道格式化没有偏移量的时区吗?

javascript - 为什么 Angular4 Router 在 <router-outlet> 之外渲染元素

angular - Angular 2 中的@angular 是什么?

javascript - Angular 2模拟Http get()返回本地json文件

widget - 在表单 <select> 元素中,如何使用 onchange 事件处理程序直接链接到所选选项?