All files / src/lib/forms/directives input-value.directive.ts

100% Statements 32/32
100% Branches 13/13
100% Functions 11/11
100% Lines 28/28

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 661x 1x           1x         2x 14x 6x     8x 8x               7x 7x   7x 7x   7x 4x     7x       1x 1x       1x 1x     1x 7x     1x 4x     1x 4x     1x 1x   1x  
import {Directive, ElementRef, HostBinding, HostListener, Optional, Self} from '@angular/core';
import {ControlValueAccessor, FormGroupDirective, NgControl, NgForm} from '@angular/forms';
 
@Directive({
    /* tslint:disable:directive-selector */
    selector: 'anj-input'
})
export class InputValueDirective implements ControlValueAccessor {
 
    public onChange: (value: any) => void;
    public onTouched: () => void;
 
    @HostBinding('attr.invalid') get isInvalid(): boolean {
        if (!this.ngControl) {
            return false;
        }
 
        const isSubmitted = (this.parent && this.parent.submitted);
        return this.ngControl.invalid && (this.ngControl.touched || isSubmitted);
    }
 
    private readonly parent: NgForm | FormGroupDirective | null;
 
    constructor(
        @Optional() parentForm: NgForm,
        @Optional() parentFormGroup: FormGroupDirective,
        @Optional() @Self() private ngControl: NgControl,
        private element: ElementRef
    ) {
        this.onChange = () => {/**/};
        this.onTouched = () => {/**/};
 
        if (this.ngControl) {
            this.ngControl.valueAccessor = this;
        }
 
        this.parent = parentForm ? parentForm : parentFormGroup ? parentFormGroup : null;
    }
 
    @HostListener('anjChange', ['$event.detail.value'])
    public _onChange(value: any) {
        this.onChange(value);
    }
 
    @HostListener('anjBlur')
    public _onBlur() {
        this.onTouched();
    }
 
    public writeValue(value: any) {
        this.element.nativeElement.value = value;
    }
 
    public registerOnChange(fn: (value: any) => void) {
        this.onChange = fn;
    }
 
    public registerOnTouched(fn: () => void) {
        this.onTouched = fn;
    }
 
    public setDisabledState(disabled: boolean) {
        this.element.nativeElement.disabled = disabled;
    }
}