I'm using Angular 4 with reactiveforms, momentjs, and primeng calendar I'm tying to use setValue
and have tried patchValue
on a reactiveForm field which contains a Date. This date has been created via a primeng calendar.
purchaseDate: Sat Sep 02 2017 00:00:00 GMT+0100 (GMT Daylight Time)
I use this 'date' to do a couple of things and then onSumbit of the form I convert the date using momentjs
to a clean format ready for the backend to accept (i.e. YYYY.MM.DD) using.moment().format(....
However when I run the .setValue
I'm getting the following console error ERROR Missing number at position 0
and can't figure out why.
// convert the date
let newDate = moment(this.form.get('purchaseDate').value).format('YYYY.MM.DD');
// let newDate = moment(this.form.get('purchaseDate')).format('YYYY.MM.DD');
// with or without .value - display the same below (2017.09.01)
console.log(newDate); // 2017.09.01
this.form.get('purchaseDate').setValue(newDate);
// if I create a seperate (empty) reactiveForms field to test against
this.form.get('testField').setValue(newDate) // this works fine
I have traced the issue down to when i try to set / patch the primeng calendar value - for some reason is doesn't like to be changed.
UPDATED monent format
The issue seams to be happening on the setValue now getting the following error
Unexpected literal at position 2 at viewWrappedDebugError
The thing is that PrimeNG date picker expects to receive instance of
Date
class as a value and it returns instance of aDate
class as value. So that's why your attempts to put object of other types in there failed.It's not clear why you attempt to call
setValue()
in the submit handler.If your goal is to modify value programmatically follow suggestion from VincenzoC in comments - modify object and transform it back to
Date
object before passing it tosetValue()
.If your goal is to format
Date
object for submitting to backend, you don't need to callsetValue()
at all. FormatDate
object to string and pass this string instead ofDate
object to the backend API. If you submitting wholevalue
object from form you can modify it this way before submitting: