Giter Club home page Giter Club logo

angular-date-value-accessor's Introduction

DateValueAccessor for Angular

NPM version Tests

A set of ControlValueAccessors for Angular to work with Browser's native date input elements. Now you can use <input type="date"> directly with two-way data bindings (ngModel) as well as with reactive forms (formControlName/formControl). Choose freely between date objects and ISO-formatted strings.

Releases

The latest version is v3.0.0. Please refer to the releases page to see which version of the package is compatible with which version of Angular and to find out what new features were rolled out at which point in time.

Demo

Here you can see the DateValueAccessor - the binding works! Changes to the input field are propagated to the model.

Example: works

And here you can see the LocalDateValueAccessor ⭐️. Please notice how the date is adjusted due to the German time zone (UTC+1) and how the time offset works.

Example: works

And this shows a not working form field (the default behaviour). Changes in the input field are propagated to the model, but unfortunately the date becomes a string which is not very useful for any further processing.

Example: does not work

You can try out a full demo at the following page:
http://johanneshoppe.github.io/angular-date-value-accessor/

Installation

Download the package via NPM:

npm install angular-date-value-accessor

UTC Time or Local Time

When working with Dates in Javascript you either operate in UTC or Local Time.

  • UTC has no timezone offset.
  • Local Time depends on the host system time zone and offset.

Javascript Dates support both the UTC and the Local Time representation. Depending on the requirements of your application you can choose from these Value Accessors:

ℹ️ Hint: Most UI component libraries like Angular Material, Kendo Angular, PrimeNG implement their DatePickers operating in Local Time. The Angular Date Pipe uses the Local Time representation of the Date Object by default, too.

Installation & Usage

You have to explicitly opt-in by adding one of these attribute directives to a HTML date input control: useValueAsDate, useValueAsLocalDate, useValueAsIso or useValueAsLocalIso.

DateValueAccessor (UTC)

The original DateValueAccessor operates in UTC (Coordinated Universal Time). The HTML date input will use the UTC representation of a given Date Object. When you select a date it will output an UTC date with the time set to 00:00 (UTC).

If you are unsure what to use, use the LocalDateValueAccessor and not the DateValueAccessor. Most users will expect the input field to correlate to their local clock.

Import the standalone directive or the NgModule:

// app.module.ts

import { DateValueAccessor, DateValueAccessorModule } from 'angular-date-value-accessor';

@NgModule({
  imports: [
    DateValueAccessor
    // OR
    DateValueAccessorModule
  ]
})
export class AppModule {}

Now you can apply the useValueAsDate to your date input controls:

<!-- DateValueAccessor (UTC) --->

<input type="date"
       name="myBirthday"
       [(ngModel)]="myBirthday"
       useValueAsDate>

OR

<input type="date"
       formControlName="myBirthday"
       useValueAsDate>

LocalDateValueAccessor (Local Time) ⭐️

The improved LocalDateValueAccessor operates in your Local Time. The HTML date input will use the Local Time representation of a given the Date Object. When you select a date it will output a Local Date with the time set to 00:00 (Local Time).

Import the standalone directive or the NgModule:

// app.module.ts

import { LocalDateValueAccessor, LocalDateValueAccessorModule } from 'angular-date-value-accessor';

@NgModule({
  imports: [
    LocalDateValueAccessor
    // OR
    LocalDateValueAccessorModule
  ]
})
export class AppModule {}

Now you can apply the useValueAsLocalDate to your date input controls:

<!-- LocalDateValueAccessor (Local Time) ⭐️ --->

<input type="date"
       name="myBirthday"
       [(ngModel)]="myBirthday"
       useValueAsLocalDate>

OR

<input type="date"
       formControlName="myBirthday"
       useValueAsLocalDate>

IsoDateValueAccessor (UTC as ISO 8601 string)

This directive gets and sets ISO 8601 formatted date strings in HTML date inputs. The handling of the dates is the same as for the DateValueAccessor.

The IsoDateValueAccessor operates in UTC (Coordinated Universal Time). The HTML date input will use the UTC representation of a given ISO 8601 formatted date string. When you select a date it will output an ISO-formatted string with the time set to 00:00 (UTC).

Import the standalone directive or the NgModule:

// app.module.ts
import { IsoDateValueAccessor, IsoDateValueAccessorModule } from 'angular-date-value-accessor';

@NgModule({
  imports: [
    IsoDateValueAccessor
    // OR
    IsoDateValueAccessorModule
  ]
})
export class AppModule { }

Now you can apply the useValueAsIso to your date input controls:

<!-- IsoDateValueAccessor (UTC as ISO string) --->

<input type="date"
       name="myBirthday"
       [(ngModel)]="myBirthday"
       useValueAsIso>

OR

<input type="date"
       formControlName="myBirthday"
       useValueAsIso>

LocalIsoDateValueAccessor (Local Time as ISO 8601 string)

This directive gets and sets ISO 8601 formatted date strings in HTML date inputs. The handling of the dates is the same as for the LocalDateValueAccessor.

The LocalIsoDateValueAccessor operates in your Local Time. The HTML date input will use the Local Time representation of a given ISO 8601 formatted date string. When you select a date it will output an ISO-formatted string with a time that equals to 00:00 (Local Time).

Note: The timezone of the outputted string is always zero UTC offset, as denoted by the suffix "Z".

Import the standalone directive or the NgModule:

// app.module.ts
import { LocalIsoDateValueAccessor, LocalIsoDateValueAccessorModule } from 'angular-date-value-accessor';

@NgModule({
  imports: [
    LocalIsoDateValueAccessor
    // OR
    LocalIsoDateValueAccessorModule
  ]
})
export class AppModule { }

Now you can apply the useValueAsLocalIso to your date input controls:

<!-- LocalIsoDateValueAccessor (Local Time as ISO string) ⭐️ --->

<input type="date"
       name="myBirthday"
       [(ngModel)]="myBirthday"
       useValueAsLocalIso>

OR

<input type="date"
       formControlName="myBirthday"
       useValueAsLocalIso>

License

This code is published under the MIT license.

angular-date-value-accessor's People

Contributors

angular-cli avatar fmalcher avatar johanneshoppe avatar juerggnos avatar rijkt avatar samvloeberghs avatar spierala avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

angular-date-value-accessor's Issues

append config when use SystemJS and error

I used SystemJS to load files.
It had error: Failed to load resource: the server responded with a status of 404 (Not Found) /angular-date-value-accessor
I found the solution: add config to file systemjs.config.js.
You should change the help config for this case.

My template used:
<input type="date" [(ngModel)]="user.Birthday" useValueAsDate>
with datatype of Birthday: Date;
It could run with no error (console log no error, and I had set user.Birthday = new Date() in constructor ), when I set user.Birthday = new Date() in a click event button, and console log of Chrome had multi errors:
Uncaught (in promise): TypeError: Failed to set the 'valueAsDate' property on 'HTMLInputElement': The provided value is not a Date.
TypeError: Failed to set the 'valueAsDate' property on 'HTMLInputElement': The provided value is not a Date.
at DomRenderer.setElementProperty (node_modules/@angular/platform-browser/bundles/platform-browser.umd.js:3070:45)
at DateValueAccessor.writeValue (node_modules/angular-date-value-accessor/date-value-accessor.js:27:24)
...

Although it thrown error, the value of user.Birthday still got the date from input control and vice versus.

I found your date-accessor from http://stackoverflow.com/questions/37055311/angular2-how-to-use-javascript-date-object-with-ngmodel-two-way-binding
I tried some solutions in that post, they had problems when inputted value of year by keypress. Your solution doesn't have that problem.
I hope you check your project and fix this error.

useValueAsDate does not work

If I remove useValueAsDate from the template it seems to work fine, I guess. But if I use it my form comes blank.
"app.module.ts" as is sample code.
My template:
<div class="form-field col-md-4">
<input type="date" class="form-control" formControlName="dateOfBirth" useValueAsDate>
<p class="help-block text-danger"></p>
</div>

issue on Angular v4.0.1

hi - for some reason the date does not bind for input type="date" in Reactive Form. I use the your demo in Angular 4 but it does not work either.
Any idea what is happening? Thanks.
gov-elements-year-field

Error: Module not found: Error: Package path ./lib/local-iso-date-value-accessor is not exported from package when running `ng extract-i18n`

When executing ng extract-i18n, an error is shown:

Error: Module not found: Error: Package path ./lib/local-iso-date-value-accessor is not exported from package

The message extraction fails in fact.

Full Error Message

$ ng extract-i18n
✔ Browser application bundle generation complete.

Initial Chunk Files              | Names              |  Raw Size
main.js                          | main               |   1.97 MB | 
polyfills.js                     | polyfills          | 980.65 kB | 
runtime.js                       | runtime            |  12.15 kB | 

                                 | Initial Total      |   2.94 MB

Lazy Chunk Files                 | Names              |  Raw Size
src_app_admin_admin_module_ts.js | admin-admin-module | 339.06 kB | 
src_app_books_books_module_ts.js | books-books-module |  32.91 kB | 

Build at: 2022-08-05T19:51:26.193Z - Hash: 03fcdd87f271a332 - Time: 5846ms

./src/app/admin/book-form/book-form.component.ts:8:0-84 - Error: Module not found: Error: Package path ./lib/local-iso-date-value-accessor is not exported from package /Users/dannykoppenhagen/dev/buch/code/book-monkey5/96-i18n/node_modules/angular-date-value-accessor (see exports field in /Users/dannykoppenhagen/dev/buch/code/book-monkey5/96-i18n/node_modules/angular-date-value-accessor/package.json)


~/dev/buch/code/book-monkey5/96-i18n (i18n ✘)✹ ᐅ 

Angular 14 support

The library is currently marked as compatible with Angular ~13, which prevents users to update to Angular 14 (released recently.)

Yes, I'm happy to try out a pre-release version if you want to! :)

allow type time and datetime-local

Hello,

I wanted to use the directive on a datetime-local type input unfortunately I got the error:

InvalidStateError: Failed to set the 'valueAsDate' property on 'HTMLInputElement': This input element does not support Date values.

Whereas this input is quite a date type input. It will be very useful to be able to bear it.

Tests are broken in 1.0.0-rc.2

I would like to fix the tests before the final version 1 is released. Currently I have no idea why the tests don't work...

An error: ValueAsDate is not a date.

Hi,
I've a message and I don't understand.
I need someone to explain to me what I'm doing wrong.

My value is : "1994-01-01"
And I've a error like :

TypeError: Value being assigned to HTMLInputElement.valueAsDate is not a date.

Initial value null

My init value was null and writeValue failed.

i wrote
if(value != null)
this._renderer.setElementProperty(this._elementRef.nativeElement, 'valueAsDate', value);

Safari Support

Hi,

great work but I have one problem.
If I open your Demo Page with Safari 12 I always get the following error "The object is in an invalid state" and the input is empty.

Do you know this problem?

Thanks Thomas

local dates

I realize this isn't really an issue, but I'm curious if you could include how to get the local date to display instead of GMT. I've tried moment.js with .format() and it doesn't work unless I manually take off the 05:00 from the ISO date: 2017-03-01T08:24:24-05:00 before passing it to the Date object that is assigned to my FormControl.

Angular 10 / tslib 2.0.0 support

Updating an existing project with latest Angular CLI (10.0.0) leads to the following output when the project contains the date-value-accessor package as dependency:

                  Package "angular-date-value-accessor" has an incompatible peer dependency to "tslib" (requires "^1.10.0", would install "2.0.0").
✖ Migration failed: Incompatible peer dependencies found.
Peer dependency warnings when installing dependencies means that those dependencies might not work correctly together.
You can use the '--force' option to ignore incompatible peer dependencies and instead address these warnings later.
  See "/private/var/folders/7n/fqslh59s19v764fsyc2k8r1c0000gn/T/ng-hWI4lO/angular-errors.log" for further details.

It can be proceeded anyway when using the --force flag.

However, in the Future, the angular-date-value-accessor should be updated to support Angular 10 with tslib 2.0.0

implementing a convert to a timestamp on the fly

Hi, I need a timestamp value in my formControl and trying to implement it with your great useValueAsDate directive. (Thanks!!!)
I actually have updated writeValue() to update value in the view like this:


  writeValue(value: number): void {
    if (!value) {
      this._renderer.setElementProperty(this._elementRef.nativeElement, 'value', null);
      return;
    }
    this._renderer.setElementProperty(this._elementRef.nativeElement, 'valueAsDate', this.convertFromTimestamp(value));
  }

  convertFromTimestamp(value: number): Date {
    return new Date(value);
  }

but how to convert date value from input to model?
I realize that registerOnChange() should be updated, but how?
Does anybody have an ideas?

Compatibility with Angular 9

Hello,

I'm trying to upgrade a project from angular 8 to 9 which uses this angular-date-value-accessor. Unfortunately compilation fails because Renderer (deprecated and replaced (with Renderer2) since Angular 4 and removed since Angular 9) is imported from @angular/core module.

Would it be possible to provide a new version of this angular-date-value-accessor which is compatible with Angular 9?

Angular 13 support

The library is currently marked as compatible with Angular ~12, which prevents users to update to Angular 13 (released today.)

IE11 Support

Works great on modern browsers. Do you plan support for IE10/11 that have no support for IE?

issue on Angular v7

`


Payment Date
<input type="date" placeholder="Payment Date" class="form-control showCalenderInline"
formControlName="payment_date" useValueAsDate #payment_date
[(ngModel)]="paymentdata.payment_date" >

`

On page load the date value is not getting rendered
Capture p

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.