Angular2如何将参数传递给自定义表单控件验证器?

前端之家收集整理的这篇文章主要介绍了Angular2如何将参数传递给自定义表单控件验证器?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我写了一个非常简单的表单控件验证器:
import { Directive } from '@angular/core';
import { AbstractControl,NG_VALIDATORS } from '@angular/forms';

function checkBoxrequiredValidator(c: AbstractControl) {
    return c.value ? null : {
        required: true
    };
}



@Directive({
    selector: '[checkBox-required-validator]',providers: [
        { provide: NG_VALIDATORS,multi: true,useValue: checkBoxrequiredValidator }
    ]
})
export class CheckBoxrequiredValidator {

}

我想传递一个消息参数给我,我可以返回.我试过这个,但它不起作用:

function checkBoxrequiredValidator(c: AbstractControl,msg) {
    return c.value ? null : {
        message: msg
    };
}


@Directive({
    selector: '[checkBox-required-validator]',useValue: checkBoxrequiredValidator }
    ]
})
export class CheckBoxrequiredValidator {
    @Input('checkBox-required-validator') msg:  = 'default message';

}

任何帮助,将不胜感激

您可以将指令本身作为验证器.这样您就可以使用消息输入.
import { forwardRef } from '@angular/core';
import { Validator } from '@angular/forms';

@Directive({
  selector: '[checkBox-required-validator]',providers: [
    { 
      provide: NG_VALIDATORS,useExisting: forwardRef(() => CheckBoxrequiredValidator )
    }
  ]
})
export class CheckBoxrequiredValidator implements Validator {
  @Input('checkBox-required-validator') msg  = 'default message';

  validate(c: AbstractControl) {
    return c.value ? null : {
      required: this.msg
    };
  }
}
原文链接:https://www.f2er.com/angularjs/140350.html

猜你在找的Angularjs相关文章