Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular | How to change order of FormArray? [duplicate]

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()
} 
like image 804
Vingtoft Avatar asked Dec 23 '22 23:12

Vingtoft


2 Answers

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.

like image 160
Vato Avatar answered Dec 28 '22 09:12

Vato


You can simply remove the group from one index and insert at another:

let group = (<FormArray>this.form.get('address')).at(index);
(<FormArray>this.form.get('address')).removeAt(index);
(<FormArray>this.form.get('address')).insert(index,group);
like image 33
Sachin Gupta Avatar answered Dec 28 '22 09:12

Sachin Gupta