如何使用 Angular 中的 formArray 修补 formGroup 中的值?

How to patch values in formGroup with formArray in Angular?

一旦用户单击编辑按钮,我想以反应形式修补数据。目前,我可以用普通字段修补值。但无法修补动态字段和数组中的值。

ngOnInit() {
    this.registrationForm = this.fb.group({
      personal_details : this.fb.group({
        name: this.fb.group({
          first_name: [''],
          last_name: ['']
        }),
        about_yourself: [''],
        dob: [''],
        // lang: [''],
        languages_known: this.fb.array([]),
        willingly_to_travel: ['']
      }),
      technologies: this.fb.array([
        this.addTech()
      ]),

      certifications : this.fb.array([
        this.addCertificate()
      ]),
    });
    this.getAllTrainners();
  }

当用户单击编辑按钮时,以下功能将 运行 :

editTrainner(trainner: Trainner) {
this._trainnerservice.currentTrainner = Object.assign({}, trainner);
this.registrationForm.patchValue({
      personal_details: { type: Object,
        name: { type: Object,
            first_name: this._trainnerservice.currentTrainner.personal_details.name.first_name,
            last_name: this._trainnerservice.currentTrainner.personal_details.name.last_name
        },
        dob: this._trainnerservice.currentTrainner.personal_details.dob,
        about_yourself: this._trainnerservice.currentTrainner.personal_details.about_yourself,
        languages_known: this.fb.array([this.addlanguages_known()]),
        willingly_to_travel: this._trainnerservice.currentTrainner.personal_details.willingly_to_travel
    }
});
  }
  addlanguages_known(): any {
    const control = this.registrationForm.get('languages_known') as FormArray;
    this._trainnerservice.currentTrainner.personal_details.languages_known.forEach(x => {
        control.push(this.fb.control(''));
      });
  }

您可以在函数调用中传递准确的 FormGroup。

例如我有这个代码:

  let mainFormGroup = new FormGroup({
    myFormGroupName: new FormControl(),
    myFormArray: new FormArray([])
  });

  let mainFormGroup = new FormGroup({
    myFormGroupName: new FormControl(),
    myFormArray: new FormArray([
      new FormGroup({
      childFormControl: new FormControl(),
      })
    ])
  });

对于我的 FormArray,我使用 ngFor

<div *ngFor="let eachFormGroup of mainFormGroup.controls['myFormArray'].controls; let pointtIndex=index;">

稍后在我的循环中我使用:

(change)="onFileChanged($event, eachFormGroup)"

在我的 onFileChange 函数中,我现在可以访问 FormGroup。

  onFileChanged(event, eachFormGroup: FormGroup) {
    eachFormGroup.patchValue({
      childFormControl: 'blablabla'
    });
  }

你也可以使用 ngFor 的 Index 来使用 at(index) 访问数组控件。在我的例子中,我在 ngFor 行中有 pointtIndex。你也可以在你的函数中传递它。

myFormArray.at(pointtIndex).get('childFormControl').setValue('value');

如果您只想从组中获取价值,您可以使用

mainFormGroup.get('myFormGroupName').setValue('name'); 

mainFormGroup.patchValue({ myFormGroupName: 'name'});