?-6ren"> ?-我有一个输入控件,如下: 当我使用键盘输入日期时,它会重置为dd/MM/yyyy。鼠标工作正常。有什么建议吗? 最佳答案 Angular 2: How to use date input contr-6ren">
gpt4 book ai didi

angular - 如何在 Angular 中正确使用 <input type ="date">?

转载 作者:行者123 更新时间:2023-12-02 14:26:22 24 4
gpt4 key购买 nike

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

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

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

最佳答案

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

关于angular - 如何在 Angular 中正确使用 &lt;input type ="date">?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52200032/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com