Kasper Juner
Kasper Juner

Reputation: 952

How to format selected value and patch?

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);
});

Upvotes: 0

Views: 397

Answers (2)

Luis Reinoso
Luis Reinoso

Reputation: 758

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

Upvotes: 0

Bruno Cunha
Bruno Cunha

Reputation: 282

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});
});

Upvotes: 1

Related Questions