[英]How to construct a form (using Angular reactive forms - form builder) with live data coming from the server
I spend the last 2 days trying different ways to get the data in the right order but I just couldn't, basically I get some data from the server and display it for the client plus some extra fields which the client need to fill out.我花了最后 2 天尝试不同的方法以正确的顺序获取数据,但我做不到,基本上我从服务器获取一些数据并将其显示给客户端以及客户端需要填写的一些额外字段。
This is my data这是我的数据
formConfiguration = { // it's dynamic !! coming back from the server!
dateSupply: {
name: "dateSupply",
validators: [
Validators.required,
]
},
products: [
{
name: "product_1",
costPerUnit: 3,
quantityPerCarton: 10,
value: 0,
validators: [
Validators.required,
]
},
{
name: "product_2",
costPerUnit: 4,
quantityPerCarton: 20,
value: 0,
validators: [
Validators.required,
]
}
],
}
this is what I did这就是我所做的
createOrderForm(products) {
const group = this.formBuilder.group({});
for (let i = 0; i < products.length; i++) {
const control = this.fb.control(products[i].value, products[i].validators || []);
group.addControl(products[i].name, control);
};
return group;
};
this is what I need..这就是我需要的..
form structure:
controls:
dateSupply: FormControl,
products: FormArray,
0 : FormGroup
controls:
name: FormControl
costPerUnit: FormControl
...
1 : FormGroup
controls:
name: FormControl
costPerUnit: FormControl
...
please help..请帮忙..
You must use FormArray.您必须使用 FormArray。 I made an example on stackblitz
我在stackblitz上做了一个例子
this.form = this._fb.group({
dateSupply: this._fb.control(formConfiguration.dateSupply.name),
products: this._fb.array(
formConfiguration.products.map(({ value, validators }) =>
this._fb.group({
name: this._fb.control(value, validators || [])
}),
),
),
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.