Search code examples
angulartypescriptformsonchangereactive

Angular Reactive Form, valueChanges runs into "maximum call stack size"


I am trying to change my formarray values based on the index as soon as a change in the form occurs. The following situation is given: I have given phases each with a start and end date. Except for the first phase, the start date of a phase should always be the same as the end date of the previous phase.

I think the error occurs because the valueChanges always calls itself as the value of the form is changed at the end of the method.

  onChanges() {
this.projectForm.controls['phases'].valueChanges.subscribe(value => {
  for (var i = 1; i <= this.phasecount; i++) {
      this.projectPhases.at(i).patchValue({ pStart: value[i - 1].pEnd });                   
  }
})

}

do any of you have an idea how to work around the error (maybe a termination condition)?

Thanks in advance.


Solution

  • This line this.projectPhases.at(i).patchValue({ pStart: value[i - 1].pEnd }); triggers this event this.projectForm.controls['phases'].valueChanges and it infinite loops.

    You could set emitEvent option to false while doing patchValue :

    this.projectPhases.at(i)
    .patchValue({ pStart: value[i - 1].pEnd }, { emitEvent: false });