All files / src/lib/forms/directives min.directive.ts

100% Statements 22/22
100% Branches 10/10
100% Functions 7/7
100% Lines 18/18

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 501x 1x   8x 7x 6x 1x     5x 3x   2x                               1x   1x     9x   2x         1x 6x     1x 6x     1x  
import {Directive, HostBinding, Input, OnChanges} from '@angular/core';
import {NG_VALIDATORS, Validator, ValidatorFn, FormControl, AbstractControl} from '@angular/forms';
 
export function validateMinValueFactory(min: number = 0): ValidatorFn {
    return (c: AbstractControl) => {
        if (c.value === undefined || c.value === null) {
            return null;
        }
 
        if (Number(c.value) >= min) {
            return null;
        } else {
            return {
                min: {
                    valid: false
                }
            };
        }
    };
}
 
/* tslint:disable:directive-selector */
@Directive({
    selector: '[min][ngModel]',
    providers: [
        {provide: NG_VALIDATORS, useExisting: MinValidatorDirective, multi: true}
    ]
})
export class MinValidatorDirective implements OnChanges, Validator {
 
    @HostBinding('attr.min') public _min: number;
 
    @Input()
    get min(): number { return this._min || 0; }
    set min(min: number) {
        this._min = Number(min);
    }
 
    private validator: ValidatorFn;
 
    public ngOnChanges() {
        this.validator = validateMinValueFactory(this.min);
    }
 
    public validate(c: FormControl) {
        return this.validator(c);
    }
 
}