在 Angular 2+ 中对 FormArray 对象进行排序的理想方法是什么? [英] What is the ideal way to sort a FormArray object in Angular 2+?
问题描述
我有一个由多个表单组组成的 formArray.我需要根据数组中每个表单组中存在的布尔字段对数组进行动态排序.
I have a formArray which consist of multiple form groups. I need to sort the array dynamically based on a boolean field present in each of the form group in the array.
布尔字段是一个复选框,在任何给定的时间点只能选中一个复选框(模仿单选按钮).因此,当单击复选框时,我需要根据选择的那个对 formArray 进行排序.
The boolean field is a checkbox and at any given point of time only one checkbox can be checked (mimics radio button). So when a checkbox is clicked I need to sort the formArray based on the one that is selected.
我知道文档建议不要弄乱 formArray 中存在的 AbstractControls[],那么动态排序数组的理想方法是什么?
I know the documentation suggests not to mess with the AbstractControls[] present in the formArray, so what would be the ideal way to dynamically sort the array ?
我尝试对数组进行切片并将控件重新设置到 formArray 中,但我一直收到错误必须为表单控件提供一个名称为:'primaryIndicator'的值."
I have tried to slice the array and set the controls back into the formArray but I keep getting an error "Must supply a value for form control with name: 'primaryIndicator'."
const abstractControls = this.formArray.controls
.slice()
.sort((a, b) => {
return (a as FormGroup).get('primaryIndicator').value ? -1 : (b as FormGroup).get('primaryIndicator').value ? 1 : 0;
});
this.formArray.setValue(abstractControls);
如果这不是正确的方法,那么解决这种情况的最佳方法是什么?
If this is not the right way, what would be the best approach to solve such a scenario ?
推荐答案
我认为这不是最好的方法,但是从 formarray 获取值,用它做任何你想做的事情并修补它们.
I do not think it would be the best way, but get the values from formarray, do whatever you want with it and patch them back.
var myArray = this.formArray.value;
//do sorting here with myArray.sort
this.formArray.patchValue(myArray)
不要改变 this.formArray 的长度和模式.Patchvalue 只能修补具有相同结构的值.
Do not change the length and schema of this.formArray. Patchvalue can only patch values, if they have same structure.
这篇关于在 Angular 2+ 中对 FormArray 对象进行排序的理想方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!