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

100% Statements 38/38
100% Branches 15/15
100% Functions 11/11
100% Lines 33/33

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 66 67 68 69 70 71 72 73 74 75 76 77 781x 1x           1x         8x         2x 13x 3x     10x 10x               8x 8x   8x 8x   8x 5x     8x     1x 9x       1x   2x 1x     1x 1x 1x       1x 1x     1x 5x     1x 5x     1x 1x   1x  
import {Directive, ElementRef, EventEmitter, HostBinding, HostListener, Optional, Output, Self} from '@angular/core';
import {ControlValueAccessor, FormGroupDirective, NgControl, NgForm} from '@angular/forms';
 
@Directive({
    /* tslint:disable-next-line:directive-selector */
    selector: 'anj-radio-group, anj-select, anj-type-ahead',
})
export class SelectValueDirective implements ControlValueAccessor {
 
    /**
     * Enable two-way binding
     */
    @Output() public readonly valueChange: EventEmitter<any> = new EventEmitter<any>();
 
    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;
    }
 
    public writeValue(value: any) {
        this.element.nativeElement.value = value;
    }
 
    @HostListener('anjChange', ['$event.target'])
    public _onChange(target: HTMLInputElement) {
        // ignore the input for type-aheads
        if (target.matches('anj-input')) {
            return;
        }
 
        const value = target.value;
        this.onChange(value);
        this.valueChange.emit(value);
    }
 
    @HostListener('anjBlur')
    public _onBlur() {
        this.onTouched();
    }
 
    public registerOnChange(fn: (value: any) => void) {
        this.onChange = fn;
    }
 
    public registerOnTouched(fn: () => void) {
        this.onTouched = fn;
    }
 
    public setDisabledState(isDisabled: boolean) {
        this.element.nativeElement.disabled = isDisabled;
    }
}