Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to correctly use <input type="date"> in Angular?

Tags:

angular

I have an input control as follows:

<input type="date" (change)="getValues($event)" [ngModel]="customer.dob| date:'yyyy-MM-dd'" (ngModelChange)="customer.dob = $event">

When I use keyboard to type the date it resets to dd/MM/yyyy. Mouse works fine. Any suggestions?

like image 872
Rahul Salvi Avatar asked Oct 22 '25 15:10

Rahul Salvi


1 Answers

There is a whole article about it in Angular 2: How to use date input controls with Angular Forms.

The solution is to implement a new value accessor for date input controls:

// date-value-accessor.ts

import { Directive, ElementRef, HostListener, Renderer, forwardRef } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';

export const DATE_VALUE_ACCESSOR: any = {
  provide: NG_VALUE_ACCESSOR,
  useExisting: forwardRef(() => DateValueAccessor),
  multi: true
};

/**
* The accessor for writing a value and listening to changes on a date input element
*
*  ### Example
*  `<input name="myBirthday" type="date" />`
*/
@Directive({
  selector: '[useValueAsDate]',
  providers: [DATE_VALUE_ACCESSOR]
})
export class DateValueAccessor implements ControlValueAccessor {

  @HostListener('input', ['$event.target.valueAsDate']) onChange = (_: any) => { };
  @HostListener('blur', []) onTouched = () => { };

  constructor(private _renderer: Renderer, private _elementRef: ElementRef) { }

  writeValue(value: Date): void {
    this._renderer.setElementProperty(this._elementRef.nativeElement, 'valueAsDate', value);
  }

  registerOnChange(fn: (_: any) => void): void { this.onChange = fn; }
  registerOnTouched(fn: () => void): void { this.onTouched = fn; }

  setDisabledState(isDisabled: boolean): void {
    this._renderer.setElementProperty(this._elementRef.nativeElement, 'disabled', isDisabled);
  }
}
like image 199
Barr J Avatar answered Oct 25 '25 09:10

Barr J



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!