Issue
I have this dynamic form control
<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>
when i try to change the value of fields
this.dynamicFormGroup.controls['mobile'].setValue('');
or
this.dynamicFormGroup.patchValue({ mobile: '444' });
the value is not updating
Any solution Thanks
Solution
In your case, it is not clear what AddressInfo
is. Instead, change your code to this:
<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;
}
User may now add a value.
If your plan is to edit that value programmatically, this.dynamicFormGroup.controls['mobile'].setValue('');
will not work, since mobile
is a FormControl within a FormArray. Then, either you have you to loop through that array to change all values or you have to clarify which value should be changed.
Update
Based on your comment, I assume that your goal is to change the value of mobile, if it starts with 0 (if not, please update your question).
<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);
}
}
So if the value is 0123456789, it will be replaced with +1123456789 (you can replace +1
to whatever you want). If you want to keep +
, please ensure you have removed type="number"
or replaced it with type="tel"
.
If your goal is to change the value of first mobile field only, you can use
this.addressFormArray.at(0).get('mobile')?.patchValue("My Value");
Answered By - Reza Saadati
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.