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:
Question: How is this best implemented?
Expected result (something like):
moveUp(i: number) {
(<FormArray> this.form.controls['experiences']).at(i).moveUp()
}
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.
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);
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