如何解决在`formGroup`中添加动态控件会自动按字母顺序排序
我正在基于Form
数组,使用角度formGroup
和formcontrols
创建动态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上为您创建了一个示例。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。