在你的情况下,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
是Form数组中的FormControl.然后,要么遍历该数组以更改所有值,要么必须明确应该更改哪个值.
Update个
根据你的 comments ,我假设你的目标是改变移动端的值,如果它以0开始(如果不是,请更新你的问题).
<div class="row" formArrayName="address" *ngFor="let fields of addressFormArray.controls; let i = index">
<ng-container [formGroupName]="i">
<input (input)="updateMobile(i)" class="form-control height-reset" placeholder="Enter Mobile" name="mobile" formControlName="mobile">
</ng-container>
</div>
updateMobile(index: number) {
const formArray = this.formMain.get('address') as FormArray;
const mobileControl = formArray.at(index).get('mobile') as FormControl;
const value = mobileControl.value;
if (value.startsWith('0')) {
const modifiedValue = '+1' + value.substring(1);
mobileControl.setValue(modifiedValue);
}
}
因此,如果值为0123456789,它将被替换为+1123456789(您可以将+1
替换为您想要的任何值).如果您想保留+
,请确保您已删除type="number"
或将其替换为type="tel"
.
如果您的目标是只更改第一个移动字段的值,则可以使用
this.addressFormArray.at(0).get('mobile')?.patchValue("My Value");