如何在Angular2/4 FormArray字段中动态设置值?

如何在Angular2/4 FormArray字段中动态设置值?,angular,angular4-forms,Angular,Angular4 Forms,我有一个动态表,可以向其中添加行。如何动态设置第3列中的数据?我正在使用FormBuilder创建表单,并且有一个方法可以接受在表中动态插入行。当我在col1中写一些东西时,我订阅change并计算两个col的和,将其放在第三个col上 public sumRow() { this.myForm .get('rows') .valueChanges .subscribe((val) => {

我有一个动态表,可以向其中添加行。如何动态设置第3列中的数据?我正在使用FormBuilder创建表单,并且有一个方法可以接受在表中动态插入行。当我在col1中写一些东西时,我订阅change并计算两个col的和,将其放在第三个col上

    public sumRow() {
        this.myForm
          .get('rows')
          .valueChanges
          .subscribe((val) => {

             // latest edit
             val.foreach((item) => {
                item.col3 = item.col1 + col2;
                // But this one does not fill the col3 but 
                // it already giving the correct values
             });

             //loop to the val instead 

             // const ctrl = this.myForm.controls['rows'];
             // ctrl.controls.forEach((field) => {
             // const col1 = parseInt(field.get('col1').value, 10);
             // const col2 = parseInt(field.get('col2').value, 10);
             // const sum = col1 + col2;
             // How to set these values to col3?
             // Doesn't work: field.get('col3').setValue(sum);
        });
    }

  public createForm() {
    this.myForm = this.fb.group({
      name: ['', Validators.required],
    });
  }

  public pushRowItems(items) {
    this.myForm.addControl('rows', this.fb.array([items]));
  }

  public initItemRows() {
    return this.fb.group({
      col1: 0,
      col2: 0,
      col3: 0,
    });
  }

  public ngOnInit() {
    this.createForm();
    this.pushRowItems(this.initRowItems());
    this.sumRow();
  }

我把你上面的代码添加到我的项目中,除了一个小小的改变,它工作得很好。。。我不得不将ctrl键转换为FormArray键:

    const ctrl = <FormArray>this.customerForm.controls['addresses'];
    ctrl.controls.forEach((field) => {
      const col1 = parseInt(field.get('street1').value, 10);
      const col2 = parseInt(field.get('street2').value, 10);
      const sum = col1 + col2;
      // How to set these values to col3?
      field.get('city').setValue(sum);
    });
const ctrl=this.customerForm.controls['addresses'];
ctrl.controls.forEach((字段)=>{
const col1=parseInt(field.get('street1')。值,10);
const col2=parseInt(field.get('street2')。值,10);
常数和=col1+col2;
//如何将这些值设置为col3?
字段.get('city').setValue(总和);
});
(我的示例使用了地址,所以我只是在地址字段中填入数字来尝试这一点。)

当你说它不适合你的时候。。。你有错误吗?如果是,错误是什么

您可以在这里找到我使用的代码:


我刚刚将上面的更改添加到populateTestData方法中,它按预期工作

我要做的是跳过
valueChanges
,并使用
ngModel
的单向绑定作为列的总和。由于不知道模板的外观,您有两种选择:

将禁用的输入字段显示为第三列,或者使用隐藏的输入字段,例如显示

如果使用禁用字段,则需要使用
getRawValue()
获取禁用字段的值

通常,我不建议将
ngModel
与反应式表单一起使用,但在这种情况下,这没关系,因为我们不使用它将其绑定到TS中的单独变量

下面是使用隐藏选项时代码的外观:


{{item.controls.col3.value}


您正在使用FormBuilder吗?你能提供用FormBuilder定义你的FormGroup的代码吗?edited@Deborahk你得到了什么错误?我已经编辑了这个问题。我订阅表单更改并进行计算,并在第三列设置这些值,但我得到了无限循环错误。是的,您将得到无限循环,因为您订阅的是值更改(该代码不在原始示例中)。在valueChanges中,您正在更改值,这会触发valueChanges。