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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With