2020-04-14 11:28:33 +02:00
|
|
|
import { Directive, ElementRef, forwardRef, HostListener, Renderer2 } from '@angular/core';
|
|
|
|
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
|
2020-02-10 10:34:14 +01:00
|
|
|
|
|
|
|
export const DATE_VALUE_ACCESSOR: any = {
|
2020-04-21 10:50:26 +02:00
|
|
|
provide: NG_VALUE_ACCESSOR,
|
|
|
|
useExisting: forwardRef(() => DateValueAccessor),
|
|
|
|
multi: true,
|
2020-02-10 10:34:14 +01:00
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* The accessor for writing a value and listening to changes on a date input element
|
|
|
|
*
|
|
|
|
* ### Example
|
2020-11-03 15:44:08 +01:00
|
|
|
* `<input type="date" choice_label="myBirthday" ngModel useValueAsDate>`
|
2020-02-10 10:34:14 +01:00
|
|
|
*/
|
|
|
|
@Directive({
|
2020-04-21 10:50:26 +02:00
|
|
|
// this selector changes the previous behavior silently and might break existing code
|
|
|
|
// selector: 'input[type=date][formControlName],input[type=date][formControl],input[type=date][ngModel]',
|
2020-02-10 10:34:14 +01:00
|
|
|
|
2020-04-21 10:50:26 +02:00
|
|
|
// this selector is an opt-in version
|
|
|
|
selector: '[useValueAsDate]',
|
|
|
|
providers: [DATE_VALUE_ACCESSOR],
|
2020-02-10 10:34:14 +01:00
|
|
|
})
|
|
|
|
export class DateValueAccessor implements ControlValueAccessor {
|
2020-04-21 10:50:26 +02:00
|
|
|
@HostListener('input', ['$event.target.valueAsDate']) onChange = (_: any) => {};
|
|
|
|
@HostListener('blur', []) onTouched = () => {};
|
|
|
|
|
|
|
|
constructor(private _renderer: Renderer2, private _elementRef: ElementRef) {}
|
|
|
|
|
|
|
|
writeValue(value: Date): void {
|
|
|
|
if (!value) {
|
|
|
|
this._renderer.setProperty(this._elementRef.nativeElement, 'value', null);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
this._renderer.setProperty(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.setProperty(this._elementRef.nativeElement, 'disabled', isDisabled);
|
|
|
|
}
|
2020-02-10 10:34:14 +01:00
|
|
|
}
|