angular 2传递数组到自定义验证器(模板驱动形式)

时间:2017-04-11 09:33:00

标签: validation angular typescript

我需要将一个对象数组传递给a2自定义验证器,然后我想根据该数组中的记录验证模板驱动的表单字段的值。

但是我无法在验证器中检索对象。

我唯一能看到的是它的名字是字符串。

非常感谢任何帮助。

<label class="btn btn-default btn-sm"  
[(ngModel)]="krediHesaplamaModel.radioModelKrediTur" name="krediHesaplamaModel.radioModelKrediTur" 
btnRadio="0"  
(click)="onRadioButtonKrediHesaplamaTurChange()" krediTuruValidator="this.krediList" >

import { Directive, forwardRef, Attribute } from '@angular/core';
import { Validator, AbstractControl, NG_VALIDATORS } from '@angular/forms';
import {Kredi} from '../kredi';

@Directive({
    selector: '[krediTuruValidator][formControlName],[krediTuruValidator][formControl],[krediTuruValidator][ngModel]',
    providers: [{ provide: NG_VALIDATORS, useExisting: forwardRef(() => KrediTuruValidator), multi: true },
    ]

})


export class KrediTuruValidator implements Validator {

    constructor(  public krediTuruValidator: Kredi[]) { }

    validate(c: AbstractControl): { [key: string]: any } {
        console.log('KL' + this.krediTuruValidator[0].krediTuru); //UNDEFINED

        let v = c.value;
        return null;
    }

}

1 个答案:

答案 0 :(得分:1)

我通过将验证函数委托给组件中的另一个方法来解决了这个问题。这样我就可以访问我想要的任何对象

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


@Directive({
    selector: '[krediVadeSayisiValidator][formControlName],[krediVadeSayisiValidator][formControl],[krediVadeSayisiValidator][ngModel]',
    providers: [{ provide: NG_VALIDATORS, useExisting: forwardRef(() => KrediVadeSayisiValidator), multi: true },]

})


export class KrediVadeSayisiValidator implements Validator {

    @Input() krediVadeSayisiValidator: ValidatorFn; //same name as the selector

    validate(c: AbstractControl): { [key: string]: any } {

              return this.krediVadeSayisiValidator(c);
    }

}

如何在模板中访问它?

    <input type="number" class="form-control" name="krediVadeSayisi" [(ngModel)]="krediHesaplamaModel.krediVadeSayisi" #krediVadeSayisi="ngModel"
        required maxlength="2" [krediVadeSayisiValidator]="validateKrediVadeSayisi()" />  /*this function is inside the component*/