如何在 angular 中的 FormArray 中设置值?

How to set values in a FormArray in angular?

我试图在一个内部有一个 FormArray 的 FormGroup 中输入值,但是我对这个数组有问题,因为数据没有映射 我的表格

this.jobOpportunity = this.fb.group({
  title: ['', Validators.required],
  description: ['', Validators.required],
  requirements: this.fb.array([]),
  initDate: ['', [Validators.required, this.dateValidator]],
  endDate: ['', [Validators.required, this.dateValidator]],
  address: ['', Validators.required],
  companyId: ['', Validators.required],
  departmentId: ['', Validators.required],
  isActive: [false],
});

requirements(): FormArray {
  return this.jobOpportunity.get("requirements") as FormArray
}

newRequirement(): FormGroup {
  return this.fb.group({
     title: ''
 })
}

我尝试输入 Api returns:

的值
this.api.getByIdJobOpportunity(this.jopId.id).subscribe(
    (data: any) => {
      this.jobOpportunity.controls['title'].setValue(data.title);
      this.jobOpportunity.controls['description'].setValue(data.description);
      const dateInitSplit = data.initDate.split('T');

      //I try to map my data to the FormArray here

      this.jobOpportunity.controls['requirements'].patchValue(data.requirements);

      //I tried with setValue but this returns an error and pachValue does not enter 
      //my data

      this.jobOpportunity.controls['initDate'].setValue(dateInitSplit[0]);
      this.jobOpportunity.controls['address'].setValue(data.address);
      this.jobOpportunity.controls['companyId'].setValue(data.companyId);
      this.jobOpportunity.controls['departmentId'].setValue(data.departmentId);
      this.jobOpportunity.controls['isActive'].setValue(data.isActive);
      const dateEndSplit = data.endDate.split('T');
      this.jobOpportunity.controls['endDate'].setValue(dateEndSplit[0]);
      this.url = data.image;
      this.formTitle = 'Actualizar empleo';
      this.labelBtn = 'Actualizar';
    },
 );

参考图片

当他尝试使用 setValue() 时,他返回了这个错误

错误原因:

您正在尝试 patch/set 没有表单组的空 FormArray 值。

requirements: this.fb.array([]), 创建了一个控件 requirements,它将是一个 FormArray 但当前为空。因此,当您从 API 获得响应时,您尝试 patch/set 那个空表单数组上的值。它需要为来自 API.

的每个项目创建一个 FormGroup

解法:

假设您的 API returns requirements 的对象数组。迭代需求数组并在其中创建一个新的表单组 + 补丁值。

this.api.getByIdJobOpportunity(this.jopId.id).subscribe(
  (data: any) => {

....

if(Array.isArray(data.requirements)){
  data.requirements.forEach(item=>{
   let newControl=newRequirement(); //Creates a new formgroup
   newControl.patchValue(item); //Patch value 
   this.requirements().push(newControl); //Add the control to the FormArray
})
}

...
}