【问题标题】:Cant use formGroup.controls['xxx'].setValue('someString');不能使用 formGroup.controls['xxx'].setValue('someString');
【发布时间】:2019-08-22 22:47:04
【问题描述】:

不能使用FormGroup.controls['lable'].setValue('some string');

我的 Angular 反应式表单有 FormControls 和 FormArray。在方法中,我想在 FormArray 的某个索引处设置值。我可以在特定索引处获取 FormArray 和 FormGroup(b 是代码中某个索引处的 foormGroup)。但是在我无法为该 FormGroup 设置值之后。

表格声明(工作)

this.addUserForm = this.formBuilder.group({
    firstName: ['', Validators.required],
    lastName: ['', Validators.required],
    primaryNode: [{lable: '' , uuid: ''},Validators.required],
    email: ['', Validators.required],
    roleFormArray: this.formBuilder.array([]),
    password: ['', Validators.required],
    repeatPassword: ['', Validators.required]
});

在 FORMARRAY(WORKING) 中添加表格

roleFormArray.push(this.formBuilder.group({
      role: ['', Validators.required],
      node: [{lable: '' , uuid: ''}, Validators.required]
    }));
    let a = this.addUserForm.get('roleFormArray');

代码无效

在方法中

let b = (<FormGroup((<FormArray>this.addUserForm.controls['roleFormArray']).controls[index]));

调试器 //到现在b有数据作为FormGroup

//但是这条线不起作用

b.controls['role'].setValue('somevalue');

我想将值设置为“角色”和“节点”

【问题讨论】:

  • 您还需要提及索引,因为您是从控件操作数组。
  • 因为它是一个formArray,你应该尝试:b.controls[i].controls['role'].setValue('somevalue');

标签: angular typescript angular-reactive-forms


【解决方案1】:

因为它是一个formArray,你可以试试:

  b.controls[index].controls['role'].setValue('somevalue');

或:

  b.get([index, 'role']).setValue('somevalue');

【讨论】:

    【解决方案2】:

    这对我有用

      (((<FormArray>this.addUserForm.controls['roleFormArray']).at(someIndex)) as FormGroup).controls['role'].setValue('somestring');
    

    【讨论】:

      【解决方案3】:

      就像我在评论中提到的,您可以在表单数组中指定表单组的索引并访问该表单组的表单控件:

      b.at(index).controls['role'].setValue('somevalue');
      

      【讨论】:

        【解决方案4】:

        试试

        this.roleFormArray.setValue({
            role: 'value',
            node: 'value',
        });
        

        【讨论】:

          猜你喜欢
          • 2020-06-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-12-15
          • 1970-01-01
          • 2017-05-15
          • 1970-01-01
          相关资源
          最近更新 更多