补丁值不适用于嵌套输入反应形式 Angular 5

Patch value not working with nested inputs Reactive forms Angular 5

我正在使用 Angular 5 和响应式表单,mi 表单是使用后端提供的 JSON 动态创建的,有一些嵌套的特殊输入 3级别,它与单选按钮配合使用效果很好,但是当输入是一组嵌套复选框时,补丁值不会更改复选框的值,这是 mi 结构的示例

this.cvForm = this._fb.group({
  name: ['', [Validators.required]],
  lastname: ['', [Validators.required]],
  nested: this._fb.group({
    level1: this._fb.group({
       level2: this._fb.group({
          level3: this._fb.group({
             checkbox: [false, Validators.required]
         })
       })
     }),
   }),
 });
}

 this.cvForm 
    .get([
      'nested',
      this.nested,
      'level1',
      this.level1,
      'level2',
      this.level2,
      'level3',
      this.level3,
      'components',
      checkbox
    ]).patchValue({ checked: setValue });

编辑:

我一直在使用你们提供的示例进行大量测试,非常感谢你们的帮助。但是我看到它没有保存补丁值 o 在第一次单击时更改值,当我单击复选框后视图更改但表单中的值仍然为 false 并且第二次单击复选框时将表单中的值设置为 true ,但是视图发生了变化,基本上补丁值和设置值都是设置值,直到第二次单击表单。我不知道为什么会这样。

由于您只关心设置复选框的值,请考虑使用 patchValue

而不是通过调用 FormGroup 上的 get 方法或通过执行您所做的事情来获得确切的 FormControl 在嵌套的情况下容易出错FormGroups.

更简单的方法是创建一个与表单结构匹配的对象值,然后设置您要设置的值。

在这里,试一试:

setValue: boolean = true;
...
this.cvForm.patchValue({
  nested: {
    level1: {
      level2: {
        chekbox: setValue
      }
    }
  }
});

这里有一个 Working Sample StackBlitz 供您参考。

检查一下https://stackblitz.com/edit/angular-hqjny3它对我有用

this.cvForm.patchValue({
  nested: {
    level1: {
      level2: {
        level3: {
          chekbox: true|false
        }
      }
    }
  }
});

您只需要传递字符串数组即可得到您要查找的 FormControl

this.cvForm 
.get([
  'nested',
  'level1',
  'level2',
  'level3',
  'checkbox'
]).patchValue(setValue) 

这应该适合你。您不需要将对象传递给 patchValue,因为这是一个单一的 formControl。如果要在单个 FormGroup.

中修补多个表单控件的值,则需要传递对象

经过几个小时的研究和测试,我发现 angular 中的响应式表单不支持 object.property 语法来设置深度级别值的值,而是我这样做的:

this.cvForm.controls['nested'].controls['level1'].controls['level2'].controls['level3'].controls['checkbox'].value['checked'] = newValue;

这解决了我的问题,感谢大家的帮助。

如果您正在寻找如何更新复选框值,请尝试这种方式(对以后的类似搜索有用)

我的表单结构

更改复选框值

this.form.controls.completed['controls'].completed.value = MyBooleanValueHere;