首页 > 解决方案 > PatchValue on a nested FormArray

问题描述

I have this form that has a nested form array that holds date values. When the user selects a date, a function is called that formats the date and should update the form's value. But, I am having a hard time understanding how to get access to the specific formcontrol in the array... This is the relevant code

 constructor(private formBuilder: FormBuilder, private datepipe: DatePipe) {
    this.form = this.formBuilder.group({

      loading: this.formBuilder.array([])
    });

 }

  get loadingForm(){

    return this.form.get('loading') as FormArray
  }

  addLoadingTimes(){

    const loading = this.formBuilder.group({

      StartLoadDate: [],
      EndLoadDate: []

    })

    this.loadingForm.push(loading);
  }


  //format date from datepicker 

  changeDateTimeEvent(event:MatDatepickerInputEvent<Date>, index, controlName) {


    const d = new Date(event.value);
    const date = this.datepipe.transform(d, 'yyyyMMddHHMMss');


    this.form.controls['loading'][controlName].at(index).patchValue(date);

  }

Right now, I am trying to update the value with this line:

 this.form.controls['loading'][controlName].at(index).patchValue(date);

but, apparently, is wrong... Could anybody help?

Here is a blitz https://stackblitz.com/edit/formarray-patchvalue

标签: angularangular-reactive-formsformarray

解决方案


FormArray method has at method to access specific control use that to setValue.

Try this:

changeDateTimeEvent(event:MatDatepickerInputEvent<Date>, index, controlName) {
     const d = new Date(event.value);
     const day = this.datepipe.transform(d, 'yyyyMMddHHMMss');
     let formName : string;
     this.loadingForm.at(index).get(controlName).setValue(day);

}

Forked Example


推荐阅读