Angular对数组进行排序会导致formGroup中的最后一个控件失效。
创始人
2024-10-24 15:31:42
0

解决这个问题的一种方法是使用Angular的FormArray来替代FormGroup中的数组,并在排序后重新建立表单控件。以下是一个示例代码:

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, FormArray } from '@angular/forms';

@Component({
  selector: 'app-my-component',
  templateUrl: './my-component.component.html',
  styleUrls: ['./my-component.component.css']
})
export class MyComponentComponent implements OnInit {
  myForm: FormGroup;

  constructor(private fb: FormBuilder) {}

  ngOnInit(): void {
    this.initializeForm();
  }

  initializeForm(): void {
    this.myForm = this.fb.group({
      myArray: this.fb.array([])
    });

    // 添加初始表单控件
    this.addFormControls();
  }

  addFormControls(): void {
    const controlArray = this.myForm.get('myArray') as FormArray;

    controlArray.push(this.fb.control('Value 1'));
    controlArray.push(this.fb.control('Value 2'));
    controlArray.push(this.fb.control('Value 3'));
  }

  sortArray(): void {
    const controlArray = this.myForm.get('myArray') as FormArray;

    // 对数组进行排序
    controlArray.controls.sort((a, b) => {
      if (a.value < b.value) {
        return -1;
      } else if (a.value > b.value) {
        return 1;
      } else {
        return 0;
      }
    });

    // 重新建立表单控件
    const sortedArray = this.fb.array(controlArray.controls.map(control => control.value));
    this.myForm.setControl('myArray', sortedArray);
  }
}

上述代码中,我们使用FormArray来代替FormGroup中的数组。在initializeForm方法中,我们初始化了myForm并添加了初始表单控件。在sortArray方法中,我们对数组进行了排序,并重新建立了表单控件。

请注意,在模板中使用myForm时,需要使用formArrayNameformGroupName来正确绑定和显示表单控件。

相关内容

热门资讯

透视新版!wepoker有什么... 透视新版!wepoker有什么规律,wepoker私人局俱乐部怎么进(透视)详细教程(有挂工具)1、...
透视系统!wepoker有什么... 透视系统!wepoker有什么规律,wepoker有辅助功能吗(透视)科技教程(有挂教程)1、wep...
透视肯定!wepoker有没有... 透视肯定!wepoker有没有机器人,wepokerplus万能挂(透视)实用技巧(有挂教程)一、w...
透视教学!wepoker私人局... 透视教学!wepoker私人局辅助,wepoker辅助器激活码(透视)插件教程(有挂解密)1、任何w...
透视肯定!wepoker透视是... 透视肯定!wepoker透视是真的吗,wepoker手机版辅助(透视)必赢教程(有挂插件);一、we...
透视数据!wepoker怎么设... 透视数据!wepoker怎么设置房间,wepoker辅助透视(透视)新2025教程(有挂教程)1、在...
透视玄学!wepoker私人局... 透视玄学!wepoker私人局俱乐部,wepoker透视脚本免费下载pc(透视)AA德州教程(有挂介...
透视辅助!wepokerplu... 透视辅助!wepokerplus万能挂,如何下载wepoker安装包(透视)2025教程(有挂黑科技...
透视能赢!wepoker底牌透... 透视能赢!wepoker底牌透视脚本,wepoker数据分析工具(透视)第三方教程(有挂详情)1、实...
透视教学!wepokerplu... 透视教学!wepokerplus透视脚本免费,wepoker怎么获得好牌(透视)微扑克教程(有挂黑科...