将参数传递给Angular 7模板驱动的表单自定义验证器

问题描述 投票:0回答:1

如何将参数传递给为Angular 7中的模板驱动表单编写的自定义验证器?

我从其他多个问题和博客文章中获得了以下代码,但大多数代码都围绕Reactive表单而不是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);
    }
}

如何在这样的输入中访问传递给minValue的值

<input type="text" name="testInput" class="form-control"
        [(ngModel)]="testValue" required
        currencyMask [options]="{ thousands: ',', decimal: '.' }"
        minValue="100">
angular angular-forms angular-template-form
1个回答
0
投票

您应该使用ngOnInit钩子来初始化验证器,因为在构造函数中还没有初始化Input属性。

ngOnInit() {
   this.validator = validateMinValue(this.minValue);
}
© www.soinside.com 2019 - 2024. All rights reserved.