2

I've been trying to fill a date input with TypeScript with no luck:

I got 3 dates with the following format: dd/MM/yyyy... So, I've parsed each number to change its format to yyyy-MM-dd then assigned it to the ngModel var of each input using datepipe. I've tried different formats but it doesn't seem to work.

HTML:

<div>
    <input type="date" ngModel="inputDate | date:'yyyy-MM-dd'"">
</div>

<div>
    <input type="date" ngModel="inputDateFrom | date:'yyyy-MM-dd'"">
</div>
<div>
    <input type="date" ngModel="inputDateTo | date:'yyyy-MM-dd'"">
</div>

TS:

let dateFill = data[4] + '/' + data[5] + '/' + data[6];
let parsedDate = dateFill.split("/");

this.inputDate = this.datepipe.transform(new Date(parsedDate[2] + '-' + parsedDate[1] + '-' + parsedDate[0]), 'yyyy-MM-dd');
this.inputDateFrom = this.datepipe.transform(new Date(parsedDate[5] + '-' + parsedDate[4] + '-' + parsedDate[3]), 'yyyy-MM-dd');
this.inputDateTo = this.datepipe.transform(new Date(parsedDate[8] + '-' + parsedDate[7] + '-' + parsedDate[6]), 'yyyy-MM-dd');
1
  • Try to use the 2 way data binding, [(ngModel)]="inputDate" Commented Jul 23, 2018 at 14:17

1 Answer 1

2

In order for binding to work, you need to surround ngModel with [( like so:

<input type="date" [(ngModel)]="inputDate | date:'yyyy-MM-dd'"">

More info on binding can be found in the docs

You also can't use pipes in the ngModel binding, so you'll need to remove that:

<input type="date" [(ngModel)]="inputDate">
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks for the explanation, it's working now but for some reason the day is getting a minus 1, and sometimes the day and month combined. Examples: 01/01/2018 shows 01/31/2018, and 02/03/2018 shows 01/02/2018 (seen this just once)
In the examples above, what was data set to?
data[4, 5, 6] comes from a table with a 'raw' date passed as a string with the format dd/MM/yyyy
@prevox I meant what were the values
And what is the use of the datepipe? Could you not just construct the string yourself and pass it to inputDate? I say that because constructing a Date object is causing your issue due to timezones.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.