角 | 如何更改 FormArray 的顺序?

Vin*_*oft 4 angular angular-forms

我正在我的 Angular 应用程序中使用 FormArray 构建一个表单:

public form = new FormGroup({
   experiences: new FormArray([])
});
Run Code Online (Sandbox Code Playgroud)

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

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

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

在此处输入图片说明

问题:这是如何最好地实施的?

预期结果(类似):

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

Vat*_*ato 7

你可以交换控件。

// 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);
Run Code Online (Sandbox Code Playgroud)

有关更详细的答案,您可以查看此帖子


Sac*_*pta 5

您可以简单地从一个索引中删除该组并插入到另一个索引中:

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