0

I need to sort an array based on a control value (number type) from a formGroup inside another array:

const toSort = [
  ['key2', FormGroup: {controls: {order: 2}}],
  ['key1', FormGroup: {controls: {order: 1}}]
  ]

I need to sort them so that a form shows the controls in that specific order. I have been able to sort it but somehow when I do it, when I submit the form the last control is not updating with the new value (the rest do). If I undo the sorting and the controls sort automatically in alphabetic order all the controls update their values correctly.

This is how I sorted the array:

toSort.sort((val1, val2) => {
      return val1[1].controls.order.value - val2[1].controls.order.value;
    });

Any idea why is not working?

3 Answers 3

1

I found the solution. The problem was I was not assigning the sorted array to itself again after sorting.

const toSort = [
  ['key2', FormGroup: {controls: {order: 2}}],
  ['key1', FormGroup: {controls: {order: 1}}]
  ]
  
 toSort = toSort.sort((val1, val2) => {
  return val1[1].controls.order.value - val2[1].controls.order.value;
});

Sign up to request clarification or add additional context in comments.

Comments

0

please change

val1[1].controls.order.value - val2[1].controls.order.value
=>
val1[1].controls.order - val2[1].controls.order

https://docs.angularjs.org/api/ng/filter/orderBy

and have a look at orderBy filter

3 Comments

Change it like this? toSort.sort(val1[1].controls.order.value - val2[1].controls.order.value => val1[1].controls.order - val2[1].controls.order);
@PabloG Yeah because there is no value key
I get an error saying Cannot find name 'val1' and same form val2
0

Correct your sort function and try

and check ngForOf here

const toSort = [
  ['key2', {FormGroup: {controls: {order: 2}}}],
  ['key1', {FormGroup: {controls: {order: 1}}}]
  ]

toSort.sort((val1, val2) => {
  return val1[1].FormGroup.controls.order - val2[1].FormGroup.controls.order;
});

console.log(toSort);

3 Comments

I edited the array. val1[1] and val2[1] are already the formGroups so I don't need to access them and I can call the controls directly.
Why don't you create an example on code sandbox to get better idea of your issue codesandbox.io/s/angular
Unfortunately I can't share the code. This is a summary of the problem. The form is much more complex but in the end the problem is this when sorting

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.