【问题标题】:Getting the specified value from the FormArray in Angular 9从Angular 9中的FormArray获取指定值
【发布时间】:2020-05-07 14:24:49
【问题描述】:

我有一个 FormGroup,它有一个 FormArray 元素:

this.addForm = new FormGroup({
  id: new FormControl(''),
  user_id: new FormControl(3),
  client_id: new FormControl('', Validators.required),
  type: new FormControl('', Validators.required),
  description: new FormControl(''),
  payment_ref: new FormControl(''),
  registration_date: new FormControl(''),
  status: new FormControl('', Validators.required),
  sale_date: new FormControl(''),
  payment_date: new FormControl(''),
  total_price: new FormControl(''),
  services: new FormArray([
    new FormGroup({
      service_id: new FormControl('', Validators.required),
      description: new FormControl('', Validators.required),
      unit: new FormControl('', Validators.required),
      price: new FormControl(''),
      quantity: new FormControl(''),
      total_price: new FormControl(''),
    }),
  ])
});

在 GUI 中,我可以通过单击按钮添加新的 FormArray。 GUI 如下所示:

当我在选择服务部分选择服务时,描述和价格应自动填充数据。 这部分的代码如下所示:

getSelectedService(event,index){
console.log(event.value);
 this.http.get("http://localhost/finance/server/public/api/v1/service" + '/' + event.value)
 .toPromise().then(data => 
  {
    //console.log(data);
    this.getSelectedServiceData = data;
    // console.log(this.getSelectedServiceData.service);
    //console.log(this.addForm.get('services'));
    this.addForm.get('services').patchValue([this.getSelectedServiceData.service]);
    console.log(this.addForm.get('services').value);

  });

}

问题是,当我添加另一行并尝试从选择框中选择服务时,描述和价格会发生变化,但第一行不是指定行。 有什么帮助吗?

【问题讨论】:

  • 你可以为你的问题创建一个堆栈闪电战吗?
  • @PrinceIsNinja 我从 Laravel 获取数据,我觉得我做不了stack blitz,而且项目很复杂。
  • 如果你想访问formarray里面的数据,你需要使用(this.addForm.services as FormArray).controls[0].value 之后你需要把这个值patch到新添加的formarray

标签: angular formarray


【解决方案1】:

如果你想访问formarray里面的数据,你需要使用下面的语句:

(this.addForm.services as FormArray).controls[0].value

现在您需要将此值修补到新添加的表单数组中

【讨论】:

    猜你喜欢
    • 2020-09-27
    • 2020-06-30
    • 2018-01-29
    • 2021-09-25
    • 2018-08-05
    • 2020-10-11
    • 2020-11-11
    • 1970-01-01
    • 2021-05-20
    相关资源
    最近更新 更多