import { Directive , ElementRef , forwardRef , HostBinding , HostListener , Renderer2 } from '@angular/core' ; import { ControlValueAccessor , NG_VALUE_ACCESSOR } from '@angular/forms' ; /**
 * The accessor for writing an iso-formatted string and listening to changes on a date input element.
 *
 *  ### Example
 *  `<input type="date" name="myBirthday" ngModel useValueAsLocalIso>`
 *
 * See also:
 * What is the correct way to set and get HTMLInputElement.valueAsDate using local Dates?
 * https://stackoverflow.com/a/53033442
 */ @ Directive ( { selector : '[useValueAsLocalIso]' , providers : [ { provide : NG_VALUE_ACCESSOR , useExisting : forwardRef ( ( ) => LocalIsoDateValueAccessor ) , multi : true } ] } ) export class LocalIsoDateValueAccessor implements ControlValueAccessor { @ HostListener ( 'input' , [ '$event.target.valueAsDate' ] ) onInput = ( date ? ) => { const localDate = date ? new Date ( date . getUTCFullYear ( ) , date . getUTCMonth ( ) , date . getUTCDate ( ) ) : null ; const isoString = localDate ? localDate . toISOString ( ) : null ; this . onChange ( isoString ) ; } ; onChange : any = ( ) => { } ; @ HostListener ( 'blur' , [ ] ) onTouched = ( ) => { } ; constructor ( private renderer , private elementRef ) { } writeValue ( isoString ? ) { const date = isoString ? new Date ( isoString ) : null ; const utcDate = date ? new Date ( Date . UTC ( date . getFullYear ( ) , date . getMonth ( ) , date . getDate ( ) ) ) : null ; this . renderer . setProperty ( this . elementRef . nativeElement , 'valueAsDate' , utcDate ) ; } registerOnChange ( fn ) { this . onChange = fn ; } registerOnTouched ( fn ) { this . onTouched = fn ; } setDisabledState ( isDisabled ) { this . renderer . setProperty ( this . elementRef . nativeElement , 'disabled' , isDisabled ) ; } }