Angular 验证器指令 - 永远不会调用验证方法

Angular validator directive - validate method is never called

我有以下验证指令:

import { Directive, Input } from '@angular/core';
import { Validator, ValidationErrors, AbstractControl, NG_VALIDATORS } from '@angular/forms';
import { isNumber } from 'util';

@Directive({
    selector: '[minMaxValidator]',
    providers: [{
        provide: NG_VALIDATORS,
        useExisting: MinMaxValidatorDirective,
        multi: true
    }]    
})

export class MinMaxValidatorDirective implements Validator {

    @Input() public minValue: number = null;
    @Input() public maxValue: number = null;

    constructor() { }

    validate(c: AbstractControl): ValidationErrors {
        let result: ValidationErrors = null;

        if (isNumber(c.value)) {
            if (this.minValue !== null && this.minValue > c.value) {
                result = { message: 'Value must be greater than ' + this.minValue };
            }

            if (this.maxValue !== null && this.maxValue < c.value) {
                result = { message: 'Value must be lower than ' + this.maxValue };
            }
        }

        return result;
    }
}

我是这样使用的:

<input type="text" min-max-validator minValue="0" maxValue="1" [(ngModel)]="data.compression" />

输入呈现,但从未调用验证器中的验证方法。我在控制台中没有错误,验证器已在 app.module.ts

中注册

我错过了什么?

您应该在输入字段中使用 minMaxValidator(指令的选择器)。

<input type="text" minMaxValidator minValue="0" maxValue="1" [(ngModel)]="data.compression" />