更改动态表单控制角度的值

问题描述 投票:0回答:2

我有这个动态表单控件

<form [formGroup]="dynamicFormGroup" (ngSubmit)="onSubmit()" >

 <div class="row" formArrayName="address" *ngFor="let fields of AddressInfo.controls; let i = index">
            <ng-container [formGroupName]="i">
 <input type="number" class="form-control height-reset" placeholder="Enter Mobile" name="mobile" formControlName="mobile" />
..
</form>

当我尝试更改字段的值时

this.dynamicFormGroup.controls['mobile'].setValue('');

this.dynamicFormGroup.patchValue({ mobile: '444' });

该值未更新

任何解决方案谢谢

angular
2个回答
0
投票

我认为问题在于您在 formGroup 内的 FormArray 内使用 FormControl。 (只需查看简短的代码片段即可)

所以你的代码应该看起来像这样;

this.dynamicFormGroup.controls[index].controls['mobile'].setValue('');

<ng-container [formGroupName]="i">
也可能会破坏它。

我建议修改表格的结构,然后找到每个表格的正确“路径”。


0
投票

就您而言,不清楚

AddressInfo
是什么。相反,将您的代码更改为:

<div class="row" formArrayName="address" *ngFor="let fields of addressFormArray.controls; let i = index">
  <ng-container [formGroupName]="i">
    <input type="number" class="form-control height-reset" placeholder="Enter Mobile" name="mobile" formControlName="mobile">
  </ng-container>
</div>
get addressFormArray() {
  return this.formMain.get('address') as FormArray;
}

用户现在可以添加值。

如果您计划以编程方式编辑该值,则

this.dynamicFormGroup.controls['mobile'].setValue('');
将不起作用,因为
mobile
是 FormArray 中的 FormControl。然后,要么循环遍历该数组以更改所有值,要么必须澄清应该更改哪个值。

© www.soinside.com 2019 - 2024. All rights reserved.