0

I had an input box type data and a datapicker. I wanted to have both with the same date object because if you modify one the other should update the data, but it was not working: I had this:

<input style="width: 150px;" [(ngModel)]="currentDateFrom" type="date" pattern="\d\d\/\d\d\/\d\d\d\d">
<button (click)="hideDateFrom = !hideDateFrom;">Select</button>
<datepicker [hidden]="hideDateFrom" [(ngModel)]="currentDateFrom" [minDate]="minDate" [showWeeks]="true"></datepicker> 

But first, the input box didn't take the date when renderer, second when you modified input, datepicker didn't update and viceversa.

So I tried to change the input type to "text". In that way, it took the data when renderer. But you can't do the ngModel bidirectional (as is string type not date anymore) you should instead have:

<input style="width: 150px;" [ngModel]="currentDateFrom | date:'dd/MM/y'" (ngModelChange)="onChanges($event)" type="text" pattern="\d\d\/\d\d\/\d\d\d\d" >

like in this example but the problem between input and datepicker still remains

Community
  • 1
  • 1
Shil Nevado
  • 716
  • 1
  • 11
  • 30

1 Answers1

1

I found a solution which it took not a short time, so I share it with you.

<input #fromDate [value]="getDateFrom() | date:'dd/MM/y'" type="text" pattern="\d\d\/\d\d\/\d\d\d\d" (keyup.enter)="currentDateFrom = getAsDate(fromDate)" (blur)="currentDateFrom = getAsDate(fromDate)">

old datepicker and button are functional, Just modify input. With this input the model object is modified when a blur or keyenter event is triggered. It is easier if you give an id to the input (#fromDate).

To make it works you would need also typescript code:

    public getDateFrom():number {
        return this.currentDateFrom && this.currentDateFrom.getTime() || new Date().getTime();
    }
    public getAsDate(date: HTMLInputElement) {
        let data = new Date();
        if (date.validity.valid && date.value != "") {
            let values =  date.value.split("/")
            //Day
            data.setDate(Number.parseInt(values[0]))
            //Month
            data.setMonth(Number.parseInt(values[1])-1)
            //Year
            data.setFullYear(Number.parseInt(values[2]))

            return data;
        }
        return null;
    }

Maybe the return null is not the best solution but the main problem of link input-datepicker is resolve.

Shil Nevado
  • 716
  • 1
  • 11
  • 30