All files / src/lib/forms/directives max.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   3x         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 validateMaxValueFactory(max: number = 0): ValidatorFn {
    return (c: AbstractControl) => {
        if (c.value === undefined || c.value === null) {
            return null;
        }
 
        if (Number(c.value) <= max) {
            return null;
        } else {
            return {
                max: {
                    valid: false
                }
            };
        }
    };
}
 
/* tslint:disable:directive-selector */
@Directive({
    selector: '[max][ngModel]',
    providers: [
        {provide: NG_VALIDATORS, useExisting: MaxValidatorDirective, multi: true}
    ]
})
export class MaxValidatorDirective implements OnChanges, Validator {
 
    @HostBinding('attr.max') public _max: number;
 
    @Input()
    get max(): number { return this._max || 0; }
    set max(max: number) {
        this._max = Number(max);
    }
 
    private validator: ValidatorFn;
 
    public ngOnChanges() {
        this.validator = validateMaxValueFactory(this.max);
    }
 
    public validate(c: FormControl) {
        return this.validator(c);
    }
 
}