angularangular-formsangular-template-form

Pass parameter to Angular 7 template driven form custom validator


How can I pass a parameter to a custom validator written for a Template Driven Form in Angular 7?

I've got the following code put together from multiple other questions and blog posts, but most center around Reactive forms rather than tempalte.

import { AbstractControl, ValidatorFn, NG_VALIDATORS, Validator, FormControl } from '@angular/forms';
import { Directive, Input } from '@angular/core';

// validation function
function validateMinValue(minValue: number): ValidatorFn {
    return (c: AbstractControl) => {

        console.log(minValue); 
        return null;
    }
}

@Directive({
    selector: '[minValue][ngModel]',
    providers: [
        { provide: NG_VALIDATORS, useExisting: MinValueValidator, multi: true }
    ]
})
export class MinValueValidator implements Validator {
    @Input("minValue") minValue;
    validator: ValidatorFn;

    constructor() {
        this.validator = validateMinValue(this.minValue);
    }

    validate(c: FormControl) {
        return this.validator(c);
    }
}

How could I access the value passed to minValue in an input like this

<input type="text" name="testInput" class="form-control"
        [(ngModel)]="testValue" required
        currencyMask [options]="{ thousands: ',', decimal: '.' }"
        minValue="100">

Solution

  • You should be using ngOnInit hook to initialize validator since there is no Input property initialized in constructor yet.

    ngOnInit() {
       this.validator = validateMinValue(this.minValue);
    }
    

    This way the initialized value will be passed to your validator.

    Another way is to simple define validator within your custom directive and take minValue from current context this:

    export class MinValueValidator implements Validator {
        @Input("minValue") minValue;
    
        validate(c: FormControl) {
            console.log(this.minValue); 
            return null;
        }
    }