I am trying to update a specific value on an formArray using insert(). I initialize form on ngOninit() like this:
this.myForm = this.fb.group({
exercises: this.fb.array([]),
type: new FormControl(),
day: new FormControl(),
sets: this.fb.array([]),
reps: this.fb.array([]),
});
I have an input where on change i call the below function but when i try to insert a new value with the array's index I get the value pushed.
onSetsChange(sets, index){
var setsFormArray = <FormArray>this.myForm.controls.sets;
setsFormArray.insert(index, new FormControl(sets));
}
The html code is below:
<div class="col-md-3">
<select class="form-control input-sm" (change)="onSetsChange($event.target.value, exerciseIndex)">
<option *ngFor="let set of sets; let i = index;">{{set}}</option>
</select>
</div>
The exerciseIndex I pass is from a loop that it doesn't show up.
What i am doing wrong and the value it's not updating? Thank you
Try using patchValue
:-
public ngOnInit() {
const arr = new FormArray([
new FormControl(),
new FormControl()
]);
let control = arr.controls[0];
setTimeout(() => control.patchValue("new-val"), 250); // Set value to "new-val"
setTimeout(() => console.log(control.value), 350); // Logs "new-val"
}