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

时间:2019-09-18 11:23:14

标签: angular formarray formgroups

一旦用户单击“编辑”按钮,我想以反应形式对数据进行修补。目前,我能够使用常规字段来修补值。但是无法修补动态字段和数组中的值。

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(''));
      });
  }

1 个答案:

答案 0 :(得分:2)

您可以在函数调用中传递确切的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'});