What is the ideal way to sort a FormArray object in Angular 2+?

Adnan Mamajiwala picture Adnan Mamajiwala · Mar 8, 2018 · Viewed 8.1k times · Source

I have a formArray which consist of multiple form groups. I need to sort the array dynamically based on a boolean field present in each of the form group in the array.

The boolean field is a checkbox and at any given point of time only one checkbox can be checked (mimics radio button). So when a checkbox is clicked I need to sort the formArray based on the one that is selected.

I know the documentation suggests not to mess with the AbstractControls[] present in the formArray, so what would be the ideal way to dynamically sort the array ?

I have tried to slice the array and set the controls back into the formArray but I keep getting an error "Must supply a value for form control with name: 'primaryIndicator'."

const abstractControls = this.formArray.controls
          .slice()
          .sort((a, b) => {
            return (a as FormGroup).get('primaryIndicator').value ? -1 : (b as FormGroup).get('primaryIndicator').value ? 1 : 0;
          });
        this.formArray.setValue(abstractControls);

If this is not the right way, what would be the best approach to solve such a scenario ?

Answer

Lorfme picture Lorfme · Mar 16, 2018

I do not think it would be the best way, but get the values from formarray, do whatever you want with it and patch them back.

var myArray = this.formArray.value;
//do sorting here with myArray.sort 
this.formArray.patchValue(myArray)

Do not change the length and schema of this.formArray. Patchvalue can only patch values, if they have same structure.