Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does sorting Angular reactive form array really requires sorting both controls and value?

I've implemented formArray sortBy function in my angular app by sorting the formArray value and patch it after the sorting.

sortBy(FieldName: string) {
  let array = this.myItems.value;
  array.value.sort((a, b) => a[FieldName] - b[FieldName]);
  array.controls.sort((a, b) => a.value[FieldName] - b.value[FieldName]);
  this.myForm.controls.myItems.patchValue(array);
}

Working Stackblitz example

As you can see I had to sort both the formArray controls and its value.

My question is, Should I really sort it both or there is a better practice or a build in way of doing it. It looks like the controls and the value should be binded somehow.

like image 845
ShayD Avatar asked Dec 10 '25 07:12

ShayD


1 Answers

Just sorting by control is enough.

First, set myItem to this.form without bracket.

this.myForm = this.formBuilder.group({
  header: ['hello form'],
  myItems: myFormArray,
});

Then sort your FormArray by controls.

sortBy(FieldName: string) {
  this.myItems.controls.sort((a, b) => a.value[FieldName] - b.value[FieldName]);
}

If you need sorted myArray, you can get it by this.myForm.getRawValue().myItems.

like image 162
N.F. Avatar answered Dec 11 '25 22:12

N.F.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!