ng2-ui / datetime-picker

Angular2 DateTime Picker
https://ng2-ui.github.io/#/datetime-picker
MIT License
121 stars 62 forks source link

Update datepicker value programmatically #76

Closed rvdhooft closed 7 years ago

rvdhooft commented 7 years ago

Changing a datetime value programmatically seems to show an unformatted version of the date. Currently the datepicker will show the initial value correctly, but when updated it will show the given string.

Please see a simplified fork of your Plunker for an example: https://plnkr.co/edit/oPKqzvMLd5fIadztz1na?p=preview

allenhwkim commented 7 years ago

Thank you for reporting this with example.

ng-model change should call formatting of value, but it seems not.

@Krisa Do you have time to look into it?

uvconnects commented 7 years ago

Yes I am having the same Problem. Will this be fixed.?

allenhwkim commented 7 years ago

NOTE: this hasn't implemented yet, but writing it as a note. the change is implemented in branch 76-format-value-programmatically

I have tried many ways to resolve this issue. However, I couldn't come with a good solution to change(reformat) ngModel value when ngModel changes

The following is how we can do for now.

Ng2DatetimePickerDirective is exported as 'ng2DatetimePickerfor external access. You can now use its formatter,formatDate(date)`

In your app, you find instance of the directive using @ViewChild.

In your html declare reference as #var=ng2DatetimePicker as follows

       <input 
         [(ngModel)]="gmtDate" 
         #ng2DatetimePicker=ng2DatetimePicker
         ng2-datetime-picker
         date-format="MM-DD-YYYY" />

In your app, define @ViewChild instance as following

 @ViewChild('ng2DatetimePicker') myDatetimePicker;

Now you can access the formatter of datetime picker outside

this.myNgModel = this.ng2DatetimePicker.formatDate('2016-11-03T22:00:00Z');

Please refer to app directory component in this repo.

rvdhooft commented 7 years ago

Any update on when this will be merged in?

allenhwkim commented 7 years ago

@rvdhooft sorry. I forgot about it. I will make merge soon in a day or two.

allenhwkim commented 7 years ago

Found out that it's not possible to format ngModel value AGAIN, when ngModel is changed.

Thus, when you change a variable, please assign it as a string if you want it to be formatted.

There are two functions provided for this purpose

If your value is a Date, call Ng2Datetime.formatDate(myDate, myFormat) e.g., Ng2Datetime.formatDate(new Date(), 'DD/MM/YYYY hh:mm')

If your value is a string, you can call Ng2Datetime.parseDate(myString, parseFormat) to get a date. e.g., Ng2Datetime.parseDate('27/01/2017 13:34 -05:00', DD/MM/YYYY HH:mm Z )

The following example is used in the app directory.

import { Ng2Datetime } from 'ng2-datetime-picker';
...
    this.dateWithTimezone = Ng2Datetime.formatDate(myDate, this.timezoneFormat);