如何在Angular中正确使用<input type =“ date” />?

时间:2018-09-06 08:44:47

标签: angular

我有一个输入控件,如下所示:

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

当我使用键盘输入日期时,它会重置为dd/MM/yyyy。鼠标工作正常。有什么建议吗?

1 个答案:

答案 0 :(得分:3)

Angular 2: How to use date input controls with Angular Forms中有整篇文章。

解决方案是为日期输入控件实现一个新的值访问器:

// 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);
  }
}