Friday 4 December 2020

Default Date to JSON conversion format in Angular app

Suppose a component (inside the angular app) having several reactive forms containing datepickers (I'm using mat-datepicker from angular material lib) and other inputs. After a user hit "Submit" button I send the value of forms to backed (with HttpClient.post). The problem is that datepicker fields are serialized as "2020-11-18T22:00:00.000Z" (obviously Date.toJSON() method is called) while backend expects other format.

Note that I'm using formly lib to build my forms, cause set of components on each form may vary. You might not be familiar with formly but anyway set of datepickers may vary as well, so I can't convert datepicker fields directly cause I don't know the exact list of date fields in a place where I send the value of forms.

Is there an elegant solution to my problem? Can't think up something better than monkey-patching Date.prototype.toJSON() or looping through objects sent on the server, check the type of fields and changing field if it's a Date? I can't find a way to set the format of value output by datepicker either in material or in formly.



from Default Date to JSON conversion format in Angular app

No comments:

Post a Comment