我写了一个非常简单的表单控件验证器:
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'; }
任何帮助,将不胜感激
您可以将指令本身作为验证器.这样您就可以使用消息输入.
原文链接:https://www.f2er.com/angularjs/140350.htmlimport { 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 }; } }