Angular |如何更改 FormArray 的顺序?
Angular | How to change order of FormArray?
我正在 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);
}
一项新要求是允许用户更改之前输入体验的顺序:
问题:如何最好地实施?
预期结果(类似):
moveUp(i: number) {
(<FormArray> this.form.controls['experiences']).at(i).moveUp()
}
你可以交换控件。
// 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);
要获得更详细的答案,您可以。
您可以简单地从一个索引中删除该组并在另一个索引中插入:
let group = (<FormArray>this.form.get('address')).at(index);
(<FormArray>this.form.get('address')).removeAt(index);
(<FormArray>this.form.get('address')).insert(index,group);
我正在 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);
}
一项新要求是允许用户更改之前输入体验的顺序:
问题:如何最好地实施?
预期结果(类似):
moveUp(i: number) {
(<FormArray> this.form.controls['experiences']).at(i).moveUp()
}
你可以交换控件。
// 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);
要获得更详细的答案,您可以
您可以简单地从一个索引中删除该组并在另一个索引中插入:
let group = (<FormArray>this.form.get('address')).at(index);
(<FormArray>this.form.get('address')).removeAt(index);
(<FormArray>this.form.get('address')).insert(index,group);