简体   繁体   English

Angular PatchValue不适用于FormArray

[英]Angular PatchValue is not working with FormArray

I am trying to patch a value so my input works like ng model 我正在尝试修补一个值,所以我的输入就像ng模型一样

here's the code 这是代码

 this.purchaseOrderForm.patchValue({
      itemForm: {
        inputSubTotal: this.tempSellPrice.valueOf().toString()
      }

    });

but it doesn't work 但这不起作用

 this.purchaseOrderForm.at(i).patchValue({
      itemForm: {
        inputSubTotal: this.tempSellPrice.valueOf().toString()
      }

    });

doesn't work also, i = index count. 也无法正常工作,我=索引计数。

is there a way to update my form without saving it yet? 有没有一种方法可以保存我的表单呢?

unfortunately, you can't patch or set a value directly onto a form array, you need to patch or set the values of the form groups / controls within it, like so: 不幸的是,您不能直接在表单数组上修补或设置值,而是需要在其中修补或设置表单组/控件的值,如下所示:

  onChangeState(i){
    const fg = this.itemsArray.at(i);
    const fgValue = fg.value;
    fg.patchValue({
      total: fgValue.fvalue + fgValue.svalue
    });
  }

here is a blitz demo: https://stackblitz.com/edit/angular-wyly3s?file=src/app/app.component.ts 这是一个闪电战演示: https : //stackblitz.com/edit/angular-wyly3s? file = src/app/ app.component.ts

I cant' say what exactly is wrong in your question code without knowing the true structure of the form you're working with 我不能在不知道您正在使用的表单的真实结构的情况下说出您的问题代码中到底有什么问题

I took a look at you StackBlitz example here https://stackblitz.com/edit/angular-c6xqxm and I think I found the issue. 我在这里查看了您的StackBlitz示例https://stackblitz.com/edit/angular-c6xqxm ,我想我发现了问题。 You have to nest the [formGroupName]="1" in a child element of the *ngFor 您必须将[formGroupName] =“ 1”嵌套在* ngFor的子元素中

Instead of 代替

<div *ngFor="let group of itemsArray.controls; let i = index;" [formGroupName]="i"> 

    //your code...      

</div>

try 尝试

<div *ngFor="let group of itemsArray.controls; let i = index;" >
  <div [formGroupName]="i"> <----------

    //your code...

  </div>
</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM