Search code examples
angularangular-forms

Angular | How to change order of FormArray?


I'm building an a form using FormArray in my Angular app:

public form = new FormGroup({
   experiences: new FormArray([])
});

Users can add experiences to the array:

addExperience(lotsOfVars) {
   const formGroup = new FormGroup({ /* creating a formgroup*/})
   (<FormArray> this.form.get('experiences')).push(formGroup);
}

A new requirement is to allow users change the order of previously entered experiences:

enter image description here

Question: How is this best implemented?

Expected result (something like):

moveUp(i: number) {
  (<FormArray> this.form.controls['experiences']).at(i).moveUp()
} 

Solution

  • you could just swap the controls.

    // clone object (otherwise only pointer/reference is saved).
    const temp = Object.assign({}, (<FormArray> this.form.controls['experiences']).at(i - 1).value);
    (<FormArray> this.form.controls['experiences']).at(i - 1).setValue((<FormArray> this.form.controls['experiences']).at(i).value);
    (<FormArray> this.form.controls['experiences']).at(i).setValue(temp);
    

    for more detailed answer you could check this post.