简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM