0

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

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

A minute ago, I was able to solve it like this: let loadingGroup = this.loadingForm.controls[index] as FormGroup ; loadingGroup.controls[controlName].patchValue(day); but this is much sleeker.. Thanks you!!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.