【问题标题】:Angular FormGroup focus out issue on key press. Not able to enter more than 1 characterAngular FormGroup 关注按键问题。无法输入超过 1 个字符
【发布时间】:2020-10-12 12:42:19
【问题描述】:

我正在尝试遍历表单控件并尝试显示字段。这些字段的显示没有任何问题,并且还可以正确保存绑定值并显示输出。我面临的问题是,在这些字段上按键时,光标失去焦点并且无法输入超过 1 个字符。

我已经简化了项目并在下面创建了演示。添加了 2 个字段,1 个使用正常循环,另一个未使用控制循环。不知道出了什么问题。

https://stackblitz.com/edit/angular-ivy-ndnzjd

【问题讨论】:

  • 你为什么使用控制循环,目的是什么?
  • @Chellappanவ,我想显示迭代 group.controls 的表单控件。该演示只是显示一个静态字段,所以请不要混淆。我想简化这个例子。从 stackblitz 演示中你知道为什么我一次不能输入超过 1 个字符并且焦点消失了吗?

标签: angular angular-reactive-forms reactive-forms formarray formgroups


【解决方案1】:

每次输入字段的值发生变化时,都会调用 toArray() 方法并重新渲染 ngFor 中的所有元素,这就是为什么要关注输入输出。

您可以通过在 ngFor 上使用 trackBy 功能来解决此问题。 trackBy 函数将索引和当前项作为参数,需要返回该项的唯一标识符。

component.html

<div *ngFor="let item of toArray(form.controls);trackBy:trackByIndex" class="form-row">not working
          <input [formControlName]="mytestfield" [id]="mytestfield" />
 </div>

component.ts

 trackByIndex(index,value){
    return index;
  }

Example

【讨论】:

    猜你喜欢
    • 2017-09-12
    • 1970-01-01
    • 1970-01-01
    • 2017-01-05
    • 1970-01-01
    • 2011-12-29
    • 1970-01-01
    • 2020-03-21
    • 2015-04-15
    相关资源
    最近更新 更多