So after using FormArrayExtended's setValue with the value being an array of two formGroup entries, containing one of id: 4 and id -1, I see afterwards that both entries in the controls are set to -1. I find out that this is because both controls at index 0 and index 1 are indeed the same control after I have run setValue. But why? Well, it turns out my FormArrayExtended actually had 3 controls, the 3rd one being a duplicate of the second, although the value returned by the control is still an array of two entries.
How this happened I am not sure, but I guess as Angular forms has an updateValueAndValidity method which is responsible for updating the value, maybe this is technically not an error and just some background state not supposed to be exposed. (I certainly never inteded to add a 3rd control, still looking into this).
Now whether you believe this is truly a valid state for a formArray to be in, I noticed that the setSize method removes the first control first. Changing it to remove the last one instead fixes my problem, and will be more efficient due to not having to move the array content forward. And in the case someone actually intended to have the same formGroup at two indexes of an array, well, this would fix their duplicate controls being moved around also.
The change I suggest is from this:
setSize(size: number) {
while (size < this.controls.length) this.removeAt(0);
while (size > this.controls.length) this.push(this.createControl());
}
to this:
setSize(size: number) {
while (size < this.controls.length) this.removeAt(this.controls.length-1);
while (size > this.controls.length) this.push(this.createControl());
}
So after using
FormArrayExtended
'ssetValue
with the value being an array of twoformGroup
entries, containing one ofid
: 4 andid
-1, I see afterwards that both entries in the controls are set to -1. I find out that this is because both controls at index 0 and index 1 are indeed the same control after I have runsetValue
. But why? Well, it turns out myFormArrayExtended
actually had 3 controls, the 3rd one being a duplicate of the second, although thevalue
returned by the control is still an array of two entries.How this happened I am not sure, but I guess as Angular forms has an
updateValueAndValidity
method which is responsible for updating the value, maybe this is technically not an error and just some background state not supposed to be exposed. (I certainly never inteded to add a 3rd control, still looking into this).Now whether you believe this is truly a valid state for a
formArray
to be in, I noticed that thesetSize
method removes the first control first. Changing it to remove the last one instead fixes my problem, and will be more efficient due to not having to move the array content forward. And in the case someone actually intended to have the sameformGroup
at two indexes of an array, well, this would fix their duplicate controls being moved around also.The change I suggest is from this:
to this: