File

src/app/custom-lib/date-value-accessor/date-value-accessor.ts

Description

The accessor for writing a value and listening to changes on a date input element

Example

<input type="date" name="myBirthday" ngModel useValueAsDate>

Implements

ControlValueAccessor

Metadata

Providers DATE_VALUE_ACCESSOR
Selector [useValueAsDate]

Index

Methods
HostListeners

Constructor

constructor(_renderer: Renderer2, _elementRef: ElementRef)
Parameters :
Name Type Optional
_renderer Renderer2 No
_elementRef ElementRef No

HostListeners

blur
blur()
input
Arguments : '$event.target.valueAsDate'
input()

Methods

registerOnChange
registerOnChange(fn: (_: any) => void)
Parameters :
Name Type Optional
fn function No
Returns : void
registerOnTouched
registerOnTouched(fn: () => void)
Parameters :
Name Type Optional
fn function No
Returns : void
setDisabledState
setDisabledState(isDisabled: boolean)
Parameters :
Name Type Optional
isDisabled boolean No
Returns : void
writeValue
writeValue(value: Date)
Parameters :
Name Type Optional
value Date No
Returns : void
import {Directive, ElementRef, forwardRef, HostListener, Renderer2} 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 type="date" name="myBirthday" ngModel useValueAsDate>`
 */
@Directive({
    // 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]',

    // this selector is an opt-in version
    selector: '[useValueAsDate]',
    providers: [DATE_VALUE_ACCESSOR]
})
export class DateValueAccessor implements ControlValueAccessor {

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

result-matching ""

    No results matching ""