【问题标题】:In Angular, how to get index from a FormArray object?在 Angular 中,如何从 FormArray 对象中获取索引?
【发布时间】:2021-09-25 17:59:00
【问题描述】:

我这里有一个表格:

 form = this.fb.group({
    username: new FormControl('', Validators.required),
    password: new FormControl('', [
      Validators.required,
      Validators.minLength(10),
    ]),
    confirmPassword: new FormControl('', Validators.required),
    firstname: new FormControl('', Validators.required),
    lastname: new FormControl('', Validators.required),
    email: new FormControl(null, [Validators.required, Validators.email]),
    phone: new FormControl(null, [
      Validators.required,
      Validators.pattern(
        '^\\s*(?:\\+?(\\d{1,3}))?[-. (]*(\\d{3})[-. )]*(\\d{3})[-. ]*(\\d{4})(?: *x(\\d+))?\\s*$'
      ),
    ]),
    roles: this.fb.array([]),
  });

请注意,只有角色是 formArray 对象, 现在我有一个与多复选框相关的功能,我想存储用户选择/检查的值:

这里是函数:

 onChange(event: any) {
    console.log(event);
    console.log(this.form);
    const roleFormArray = <FormArray>this.form.value.roles;
    if (event.target.checked) {
      roleFormArray.push(event.target.defaultValue);
    } else {
      let index = roleFormArray.value.findIndex(
        (x) => x.value == event.target.defaultValue
      );
      roleFormArray.removeAt(index);
    }
  
  }

在 HTML 上,很简单:

 <div class="form-check">
        <input
          class="form-check-input"
          type="checkbox"
          value="User"
          id="userCheck"
          (change)="onChange($event)"
        />
        <label class="form-check-label" for="userCheck"> User </label>
        <br />
        <input
          class="form-check-input"
          type="checkbox"
          value="Manager"
          id="managerCheck"
          onchange="onChange($event)"
        />
        <label class="form-check-label" for="managerCheck"> Manager </label>
</div>

所以基本上我希望我的代码运行,如果用户检查角色 - 用户,那么它应该添加到数组“用户”(这是成功的),但是当用户取消选择用户复选框时,它抛出错误 - 无法读取未定义的属性“findIndex”

不知道为什么 findIndex 不能提供来自 FormArray 的索引。 有什么建议?谢谢!!

【问题讨论】:

  • 我想下面的答案对你有帮助 let index = this.roleFormArray.findIndex(x => { if(x.value == event.target.defaultValue){ return x; } }) ; this.roleFormArray.splice(index , 1);

标签: angular formarray form-control


【解决方案1】:

您添加复选框值并从 formarray 中删除的方式是错误的。在选择时,您需要创建 formcontrol 并将其添加到 formarray。在取消选择时,您需要从 formarray 中删除 formcontrol。

onChange(event: any) {
    console.log(event);
    console.log(this.form);
    const roleFormArray = <FormArray>this.form.controls['roles']; // Corrected
    if (event.target.checked) {
      roleFormArray.push(this.fb.control(event.target.defaultValue)); // Push control not value.
    } else {
      let index = roleFormArray.controls.findIndex( // Find item from controls.
        (x) => x.value == event.target.defaultValue
      );
      roleFormArray.removeAt(index);
    }
  
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-27
    • 2021-09-10
    • 2020-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-17
    相关资源
    最近更新 更多