如何在Dart中使用Angular2实现自定义验证器?
我的代码:如何在Dart中使用Angular2实现自定义验证器?,dart,angular,Dart,Angular,我的代码: <input #rtc="ngForm" type="number" min="1" max="43200" style="text-align: center" [(ngModel)]="device.rtc" ngControl="rtc" required> HTML模板: <input #deviceRtc="ngForm" t
<input #rtc="ngForm"
type="number"
min="1"
max="43200"
style="text-align: center"
[(ngModel)]="device.rtc"
ngControl="rtc"
required>
HTML模板:
<input
#deviceRtc="ngForm"
type="number"
min="1"
max="43200"
style="text-align: center"
[(ngModel)]="device.rtc"
ngControl="ctrlRtc" <!-- also tried 'rtc'-->
>
控制台中从未显示“111”…类似于:
this.myForm = fb.group({
'rtc': ['', MyValidator.validate]
});
class MyValidator {
static Map<String, bool> validate(Control control) {
if(control.value !...) {
return {'someErrorKey': true};
}
return null;
}
}
this.myForm=fb.group({
“rtc”:['',MyValidator.validate]
});
类验证程序{
静态映射验证(控制){
if(control.value!…){
返回{'someErrorKey':true};
}
返回null;
}
}
(未测试)我认为您需要使用而不是ngControl
。您不需要#DeviceCertc
间谍
<input
type="number"
min="1"
max="43200"
style="text-align: center"
[(ngModel)]="device.rtc"
[ngFormControl]="ctrlRtc">
然后,您将看到每次输入更改时都会调用rtcvalidater(…)
。我不会费心解释验证器函数的返回类型,因为甘特已经在他的回答中证明了这一点
我没有尝试运行您的示例,但我确实有您可以尝试的方法。谢谢您的回复,您能解释一下代码的更多细节吗?我是一个既有飞镖又有棱角的新人。。。1) “这”是什么意思?上下文是组件代码吗?2) 什么是fb?不知道该解释什么。验证程序被传递到
rtc
控件['',MyValidator.validate]
“”
,是初始值,如果要应用多个验证程序,则第二个参数是单个验证程序或验证程序列表。验证器本身只是一个函数,由Angular调用,并在其中传递控件。如果该值不满足某些条件,则返回带有错误键和错误值的映射(不确定该值的用途)。从文档中看,它似乎不需要是bool
类MyComponent{Control-ctrlRtc1=new-Control(['test',rtcvalidater]);静态映射rtcvalidater(Control-Control){print(111);}}
这是我的测试代码,但print(111)从未显示过……注释似乎还没有完成。请编辑您的问题并将代码放在那里。注释中的代码很难阅读。在您问题的[][]标记(左下角)下方有一个edit
链接。Control-ctrlRtc=new-Control(['test',rtcvalidater])代码>应改为Control-ctrlRtc=new-Control('test',rtcValidator)
不带[]
否则['test',rtcValidator]
将用作控件的初始值。我遵循链接的示例,使验证工作正常
<input
type="number"
min="1"
max="43200"
style="text-align: center"
[(ngModel)]="device.rtc"
[ngFormControl]="ctrlRtc">