funky-framadate-front/mocks/old-stuff/custom-lib/date-value-accessor/date-value-accessor.ts

50 lines
1.6 KiB
TypeScript
Raw Normal View History

import { Directive, ElementRef, forwardRef, HostListener, Renderer2 } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
export const DATE_VALUE_ACCESSOR: any = {
2020-04-21 10:50:26 +02:00
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
2020-11-03 15:44:08 +01:00
* `<input type="date" choice_label="myBirthday" ngModel useValueAsDate>`
*/
@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-04-21 10:50:26 +02:00
// this selector is an opt-in version
selector: '[useValueAsDate]',
providers: [DATE_VALUE_ACCESSOR],
})
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);
}
}