0

I'm using reactive form in my Angular App, i have to format the selected value and patch it's new value to that form control.

I was trying to simply subscribe control to value change and patch new value but i get error:

Maximum call stack size exceeded

How can i format selected value of a Reactive Form control?

Here is my code:

this.ritiroForm.controls.quando.valueChanges.subscribe(() => {
  const data = new Date(this.selectedOra).toLocaleString();
  this.ritiroForm.get('quando').patchValue(data);
});
Kasper Juner
  • 832
  • 3
  • 15
  • 34

2 Answers2

1

When you use patchValue function, its fired valueChanges again, so you are making a infinite loop.

To avoid that, you can pass a parameter {emitEvent: false} in patchValue, and angular won't fire valueChangesagain.

this.ritiroForm.controls.quando.valueChanges.subscribe(() => {
  const data = new Date(this.selectedOra).toLocaleString();
  this.ritiroForm.get('quando').patchValue(data, {emitEvent: false});
});
Bruno Cunha
  • 264
  • 2
  • 5
0

I assume you are formatting date only for presentation. I suggest to use a date pipe.

For example you are calling to toLocaleString(). On my side date become 25/9/2020 9:00:10 to achieve this on angular template you should use the next:

<div> {{ this.ritiroForm.get('quando').value | date:'M/d/yy, h:mm' }}</div>

Also date pipe will format date based on locale to use you should set locale. Check this link. How to set locale in DatePipe in Angular 2?

The advantage using date pipe is that your date always become the same and only change presentation. This will be useful when you work with dates from different time zones.

More info about date pipe here: https://angular.io/api/common/DatePipe

Luis Reinoso
  • 748
  • 4
  • 13
  • i was formatting the date to pass it in correct format to the API, anyway solved by patching formatted value when submitting the .POST – Kasper Juner Sep 25 '20 at 15:00