Angular-如何对FormArray中的项目重新排序? [英] Angular - How to reorder items in FormArray?
问题描述
我有一个包含一堆控件的大型表单.在此表单中,我有一组表单组,这是我的规则".
I have a large form that contains a bunch of controls. Within this form, I have an array of form groups which are my "rules".
我需要添加更改规则顺序的功能,不仅可以更改其值,还可以更改其在DOM中的视觉位置.
I need to add the ability to change the order of the rule, not only its value but its visual place in the DOM.
这是我的设置:
这些规则中的每个规则都是具有自己的表单组等的组件.它们最初显示的顺序基于其当前存储的处理顺序值.
Each one of those rules is a component that has its own form groups etc. The order they are initially displayed is based on their current stored processing order value.
在每个规则下方,我都有一个按钮来上下移动规则,这是我正在研究的内容.
Below each rule I have a button to move the rule up or down which is what I am working on.
对于反应式表单,表单组的索引是否确定其在组件UI中的位置?例如,如果我想上移一条规则,是否可以将表格组索引更改为currentIndex-1
或将上面的规则更改为+1
以便更改位置?
With reactive forms, does the index of a form group determine its position in the component UI? For example, if I wanted to move a rule up, could I change that form groups index to currentIndex-1
and perhaps the rule above to +1
in order to change places?
我在这里的目标是能够在UI上上下移动这些组件.由于此页面上的规则数量众多,我试图远离拖放库.
My goal here is to be able to move those components up and down on the UI. I am trying to stay away from a drag and drop library due to the amount of rules on this page.
更新:
这是我的设置中的一个小插曲:
Here is a plunker of my setup:
https://plnkr.co/edit/S77zywAa7l900F0Daedv?p=preview
推荐答案
FormArray
上有几种方法,例如removeAt
和insert
,可以帮助您实现目标.
There are several methods on FormArray
like removeAt
and insert
that can help you to achieve your goal.
template.html
<button class="button" (click)="move(-1, i)">Move Up</button>
<button class="button" (click)="move(1, i)">Move Down</button>
component.ts
move(shift, currentIndex) {
const rules = this.rulesForm.get('ruleData.rules') as FormArray;
let newIndex: number = currentIndex + shift;
if(newIndex === -1) {
newIndex = rules.length - 1;
} else if(newIndex == rules.length) {
newIndex = 0;
}
const currentGroup = rules.at(currentIndex);
rules.removeAt(currentIndex);
rules.insert(newIndex, currentGroup)
}
Plunker Example
这篇关于Angular-如何对FormArray中的项目重新排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!