Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ERROR Missing number at position 0 when using setValue angular 4

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

like image 483
fidev Avatar asked Sep 05 '17 09:09

fidev


1 Answers

The thing is that PrimeNG date picker expects to receive instance of Date class as a value and it returns instance of a Date 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 to setValue().

let newDate: Date = moment(this.form.get('purchaseDate').value).add(5, 'days').toDate();
this.form.get('purchaseDate').setValue(newDate);

If your goal is to format Date object for submitting to backend, you don't need to call setValue() at all. Format Date object to string and pass this string instead of Date object to the backend API. If you submitting whole value object from form you can modify it this way before submitting:

let newDate: string = moment(this.form.get('purchaseDate').value).format('YYYY.MM.DD');
let dataForBackend = { ...this.form.value, purchaseDate: newDate };
this.myBackend.sendData(dataForBackend);
like image 106
Yaroslav Admin Avatar answered Sep 26 '22 08:09

Yaroslav Admin