typescript 更改表单数组的位置

epfja78i  于 2023-01-21  发布在  TypeScript
关注(0)|答案(3)|浏览(246)

我有一个表,在其中显示来自表单的信息,并且有一个添加记录的按钮,但是当我生成新元素时,它占据最后一个位置,我希望它占据位置0,我尝试使用拼接函数,但它不起作用,当我刷新数据源时,位置仍然与拼接前相同

my form array
  myformArray = new FormArray([
    this.formBuilder.group({
      id: [0, Validators.required],
      empleado: ["Juan Antonio Vazquez", Validators.required],
      nss: ["ass5495d", Validators.required],
      capacitacion: ["SI", [Validators.required, Validators.email]]
    })
  ])

添加新记录

addRow() {
    let a =
      this.formBuilder.group({
        id: [1, Validators.required],
        empleado: ['', Validators.required],
        nss: ["", Validators.required],
        capacitacion: ["", [Validators.required, Validators.email]]
      })
    this.myformArray.push(a);
    let fromIndex = this.myformArray.value.indexOf(a.value);
    let toIndex = 0;
    let element = this.myformArray.value.splice(fromIndex, 1)[0];
 

    this.myformArray.value.splice(toIndex, 0, element);

    this.dataSource.data = this.myformArray.controls

  }
xxhby3vn

xxhby3vn1#

Materials cdkDrag的帮助下,你可以使用moveItemInArray函数。看代码here

  • 下面是函数本身:*
export function moveItemInArray<T = any>(array: T[], fromIndex: number, toIndex: number): void {
  const from = clamp(fromIndex, array.length - 1);
  const to = clamp(toIndex, array.length - 1);

  if (from === to) {
    return;
  }

  const target = array[from];
  const delta = to < from ? -1 : 1;

  for (let i = from; i !== to; i += delta) {
    array[i] = array[i + delta];
  }

  array[to] = target;
}

就像moveItemInArray(this.myformArray, 0, 2)一样简单吧,玩得开心!

注解

clamp函数帮助获得最小值/最大值。因此,不能使用比array.length更高的to参数。

function clamp(value: number, max: number): number {
  return Math.max(0, Math.min(max, value));
}
omhiaaxx

omhiaaxx2#

我不确定这是否能解决您的问题,但是如果您想在数组的开头插入一个项,可以使用unshift方法。

hgtggwj0

hgtggwj03#

我终于明白了,我改变了表单数组值的位置,但我需要改变控件的位置

addRow() {
    let a =
      this.formBuilder.group({
        id: [1, Validators.required],
        empleado: ['', Validators.required],
        nss: ["", Validators.required],
        capacitacion: ["", [Validators.required, Validators.email]]
      })
    this.myformArray.push(a);
    let fromIndex = this.myformArray.controls.indexOf(a);
    let toIndex = 0;
    let element = this.myformArray.controls.splice(fromIndex, 1)[0];

    this.myformArray.controls.splice(toIndex, 0, element);

    this.dataSource.data = this.myformArray.controls
  }

相关问题