Angular - 如何在 FormArray 中重新排序项目?

SBB*_*SBB 16 angular

我有一个包含一堆控件的大表单。在这个表单中,我有一组表单组,它们是我的“规则”。

我需要添加更改规则顺序的功能,不仅是它的值,还有它在 DOM 中的可视位置。

这是我的设置:

在此处输入图片说明

这些规则中的每一个都是具有自己的表单组等的组件。它们最初显示的顺序基于它们当前存储的处理顺序值。

在每条规则下方,我都有一个按钮来向上或向下移动规则,这正是我正在处理的。

对于响应式表单,表单组的索引是否决定了它在组件 UI 中的位置?例如,如果我想将规则向上移动,我是否可以将该表单组索引更改为currentIndex-1或者将上面的规则+1更改为以更改位置?

我的目标是能够在 UI 上上下移动这些组件。由于此页面上的规则数量,我试图远离拖放库。

更新:

这是我的设置的一个plunker:

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

yur*_*zui 21

有几种方法FormArray一样removeAt,并insert可以帮助你实现你的目标。

模板.html

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

组件.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)
}
Run Code Online (Sandbox Code Playgroud)

Plunker 示例


Dim*_*huk 8

这是“move”方法的一个简短的 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);
}
Run Code Online (Sandbox Code Playgroud)

笨蛋的例子