使用Angular的Formarray来加载多个值。
具体解法如下:
在组件的ngOnInit方法中初始化表单控件,包括formGroup和formArray。
定义一个方法loadData()来加载数据。在这个方法中,可以调用服务从服务器获取数据,然后使用setValue()方法将数据设置到表单控件中。
在HTML模板中使用ngFor指令遍历表单控件中的每一个条目,并为每个条目定义一个表单项。
示例代码如下:
//定义一个FormGroup formGroup = new FormGroup({ customerName: new FormControl(''), orderItems: new FormArray([]) });
//初始化表单项 ngOnInit() { this.orderService.getOrder().subscribe(response => { let orderItems = response.orderItems.map(orderItem => { //为FormArray添加表单项 return this.createOrderItem(orderItem); }); this.formGroup = new FormGroup({ customerName: new FormControl(response.customerName), orderItems: new FormArray(orderItems) }); }); }
//创建一个表单项 createOrderItem(orderItem: any): FormGroup { return new FormGroup({ itemName: new FormControl(orderItem.itemName), itemPrice: new FormControl(orderItem.itemPrice) }); }
//加载数据 loadData() { this.orderService.getOrder().subscribe(response => { let orderItems = response.orderItems.map(orderItem => { return this.createOrderItem(orderItem); }); this.formGroup.setValue({ customerName: response.customerName, orderItems: orderItems }); }); }
//在模板中使用表单项