简体   繁体   English

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".在这个表单中,我有一组表单组,它们是我的“规则”。

I need to add the ability to change the order of the rule, not only its value but its visual place in the DOM.我需要添加更改规则顺序的功能,不仅是它的值,还有它在 DOM 中的可视位置。

Here is what my setup looks like:这是我的设置:

在此处输入图片说明

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.在每条规则下方,我都有一个按钮来向上或向下移动规则,这正是我正在处理的。

With reactive forms, does the index of a form group determine its position in the component UI?对于响应式表单,表单组的索引是否决定了它在组件 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?例如,如果我想向上移动一个规则,我是否可以将该表单组索引更改为currentIndex-1 ,或者将上面的规则更改为+1以更改位置?

My goal here is to be able to move those components up and down on the UI.我的目标是能够在 UI 上上下移动这些组件。 I am trying to stay away from a drag and drop library due to the amount of rules on this page.由于此页面上的规则数量,我试图远离拖放库。

Update:更新:

Here is a plunker of my setup:这是我的设置的一个plunker:

https://plnkr.co/edit/S77zywAa7l900F0Daedv?p=preview https://plnkr.co/edit/S77zywAa7l900F0Daedv?p=preview

There are several methods on FormArray like removeAt and insert that can help you to achieve your goal. FormArray上有多种方法,例如removeAtinsert ,可以帮助您实现目标。

template.html模板.html

<button class="button" (click)="move(-1, i)">Move Up</button> &nbsp; 
<button class="button" (click)="move(1, i)">Move Down</button>

component.ts组件.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 ExamplePlunker 示例

Here is a short es6 version of "move" method:这是“移动”方法的简短 es6 版本:

move(shift: number, i: number,): void {
    const { controls } = this.rulesForm.get('ruleData.rules');
    [ controls[i], controls[i+shift] ] = [ controls[i+shift], controls[i] ];
    this.rulesForm.patchValue(controls);
}

Plunker Example Plunker 示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM