在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的长度和架构.如果补丁值具有相同的结构,则它们只能补丁值.
Do not change the length and schema of this.formArray. Patchvalue can only patch values, if they have same structure.
这篇关于在Angular 2+中对FormArray对象进行排序的理想方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!