角度|如何更改FormArray的顺序?

时间:2019-04-11 08:38:13

标签: angular angular-forms

我正在Angular应用中使用FormArray构建表单:

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

用户可以向阵列添加体验:

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

一项新要求是允许用户更改以前输入的体验的顺序:

enter image description here

问题:如何最好地实施?

预期结果(类似):

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

2 个答案:

答案 0 :(得分:1)

您可以交换控件。

// 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);

有关更详细的答案,您可以check this post

答案 1 :(得分:0)

您可以简单地从一个索引中删除组,然后在另一个索引中插入:

let group = (<FormArray>this.form.get('address')).at(index);
(<FormArray>this.form.get('address')).removeAt(index);
(<FormArray>this.form.get('address')).insert(index,group);