【发布时间】:2020-09-12 04:18:03
【问题描述】:
尝试将服务器数据插入 Angular 的表单,以便 FormGroup 属性键是来自服务器数据的键。遵循 Angular 的动态表单文档,但这并不是我想要的 (https://angular.io/guide/reactive-forms#creating-dynamic-forms)。
重点是用数据填充表单并在模板中显示它,*ngFor 使用每个属性上的滑块来获取一个值。然后将数据发送回服务器。
数据对象示例:
{
"things": [
{
"thingId": 1,
"thingName": "bear"
},
{
"thingId": 2,
"thingName": "piano"
}
]
}
服务获取数据并分配给变量:
things: IThing[] = [];
getThings() {
this.thingService.getThings()
.subscribe(data => {
this.things = data.things;
});
}
我需要用从服务器获取的数据对象的值填充thingsFormGroup(或FormArray,如果需要),即thingName属性值=>“bear”,“piano”。
ngOnInit() {
this.myForm = this.fb.group({
title: ['', []],
comment: ['', []],
// need to populate the things object here, example:
things: this.fb.group([
// bear: [,[]],
// piano: [,[]]
// and so on...
])
})
this.getThings();
}
【问题讨论】:
标签: javascript arrays angular forms angular-reactive-forms