【问题标题】:Angular FormArray - Duplicate value validatorAngular FormArray - 重复值验证器
【发布时间】:2018-11-21 17:46:47
【问题描述】:

我正在使用带有反应形式的 Angular 6。其中一个表单字段是 FormArray,它在用户单击“添加”按钮时添加控件。

在FormArray中,我想检查FormControl值是否已经存在于FormArray中。

这可以正常工作,直到用户单击“添加”按钮重置先前的控件错误并将控件标记为有效,尽管它仍然具有重复值。

这是在表单数组中添加控件的函数:

onAddIPAddress() {

  if (( < FormArray > this.tcpudpAppFormGroup.get('ipaddressArray')).length < 8) {

    const control = new FormControl(null, Validators.compose([
      Validators.required,
      Validators.pattern(this.ipaddressPattern),
      this.forbiddenIPs.bind(this),
      this.onDuplicateIPFormArray.bind(this)
    ]));


    ( < FormArray > this.tcpudpAppFormGroup.get('ipaddressArray')).push(control);


  } else {
    return;
  }

}

然后,这是自定义验证器代码:

onDuplicateIPFormArray(control: FormControl): {
  [s: string]: boolean
} {

  if (
    ( < FormArray > this.tcpudpAppFormGroup.get('ipaddressArray')).length > 1 &&
    !( < FormArray > this.tcpudpAppFormGroup.get('ipaddressArray')).value.includes(null) &&
    ( < FormArray > this.tcpudpAppFormGroup.get('ipaddressArray')).value.indexOf(control.value) !== -1)

  {
    console.log(( < FormArray > this.tcpudpAppFormGroup.get('ipaddressArray')).value.indexOf(control.value));

    return {
      duplicateIP: true
    };
  }

  return null;

}

从控制台,我可以看到 IndexOf 值不正确,但无法理解原因。

有什么办法可以解决这个问题吗?

谢谢

【问题讨论】:

  • 据我了解,您将新创建的 FormControl 的值设置为 null ,然后将 null 用于 indexOf
  • 我将初始 FormControl 值设置为 null,然后在验证器中执行以下操作: - 检查 FormArray 长度是否 > 1, - 检查 FormArray 控件之一是否不为空,如果没有则为空使用获取FormControl的indexOf值

标签: angular angular-reactive-forms


【解决方案1】:

好的,所以我改变了验证的方式,看起来好多了:

  • 从单个 FormArray 控件中删除自定义验证器。

  • 将重复项自定义验证器放在 FormArray 本身上。

if ($event.value ===
  'ip-address') {
  this.tcpudpAppFormGroup.addControl('ipaddressArray', new FormArray([], Validators.compose([
    Validators.required,
    this.onDuplicateIPFormArray.bind(this)

  ])));

然后创建 FormArray 验证器作为标准函数来检测数组中的重复项:

onDuplicateIPFormArray() {

  if (( < FormArray > this.tcpudpAppFormGroup.get('ipaddressArray'))) {

    let counts = [];

    for (let i = 0; i < ( < FormArray > this.tcpudpAppFormGroup.get('ipaddressArray')).length; i++) {
      if (counts[( < FormArray > this.tcpudpAppFormGroup.get('ipaddressArray')).value[i]] === undefined) {
        counts[( < FormArray > this.tcpudpAppFormGroup.get('ipaddressArray')).value[i]] = 1;
      } else {
        console.log(counts);
        ( < FormArray > this.tcpudpAppFormGroup.get('ipaddressArray')).controls[i].setErrors({
          duplicateIP: true
        });
        
      }
    }
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-23
    • 2017-09-20
    • 1970-01-01
    • 2020-03-06
    • 1970-01-01
    • 2019-02-06
    • 1970-01-01
    • 2019-01-31
    相关资源
    最近更新 更多