在`formGroup`中添加动态控件会自动按字母顺序排序

问题描述

我正在基于Form数组,使用角度formGroupformcontrols创建动态json

let input = ['name','zip_code' 'address','field1','custom_field']; 

app.component.ts

public group: FormGroup = this.formBuilder.group({});
    
  ngOnInit() {
    for(let field in input) {
    this.group.addControl(this.input[field],new FormControl('',[]));
  }
  console.log(this.group.controls);
}

控制台输出

address: FormControl
custom_field: FormControl 
field1: FormControl 
name: FormControl 
zip_code: FormControl 

应用。 component.html

<form autocomplete="off">
  <div *ngFor="let control of group.controls | keyvalue; let i = index">
    <text-field> </text-field>
  </div>
</form>

在视图上,form字段按字母顺序显示

有什么办法可以禁用按字母顺序排列的字段排序? 我想以数组中的相同顺序显示字段。

解决方法

在为FormGroup创建数组之后,尝试将Object.keys()ngFor一起使用。像这样:

app.component.ts

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

@Component({
  selector: 'my-app',templateUrl: './app.component.html',styleUrls: [ './app.component.css' ]
})
export class AppComponent  {

  public input = ['name','zip_code','address','field1','custom_field'];

  public arrayForm: any[];

  public group: FormGroup 

  constructor(private formBuilder: FormBuilder) {
    this.group = this.formBuilder.group({});
    for (let field in this.input) {
       this.group.addControl(this.input[field],new FormControl('',[]));
    }
  console.log(this.group.controls);
  this.arrayForm = Object.keys(this.group.controls)
  console.log(this.arrayForm)
  }
}

app.component.html

<form autocomplete="off">
  <div *ngFor="let control of this.arrayForm; let i = index">
    {{control}}
    <input>
  </div>
</form>

我在Stackblitz上为您创建了一个示例。