如何在 Dart 中使用 Angular2 实现自定义验证器?
How to implement a custom validator with Angular2 in Dart?
我的代码:
<input #rtc="ngForm"
type="number"
min="1"
max="43200"
style="text-align: center"
[(ngModel)]="device.rtc"
ngControl="rtc"
required>
ngControl
不跟踪数字类型输入的有效状态。如何自己实现输入验证器?
这是我的测试代码:
飞镖:
class MyComponent
{
Control ctrlRtc = new Control('test', rtcValidator);
static Map<String, bool> rtcValidator(Control control)
{
print(111);
}
}
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;
}
}
(未测试)
我认为您需要使用 ngFormControl
而不是 ngControl
。你不需要 #deviceRtc
间谍。
<input
type="number"
min="1"
max="43200"
style="text-align: center"
[(ngModel)]="device.rtc"
[ngFormControl]="ctrlRtc">
然后你会看到你的 rtcValidator(...)
每次输入改变时都会被调用。我不会费心解释验证器函数的 return 类型,因为 Günter 已经在他的回答中证明了这一点。
我没有尝试 运行 你的例子,但我有 a working example 你可以试试。
我的代码:
<input #rtc="ngForm"
type="number"
min="1"
max="43200"
style="text-align: center"
[(ngModel)]="device.rtc"
ngControl="rtc"
required>
ngControl
不跟踪数字类型输入的有效状态。如何自己实现输入验证器?
这是我的测试代码:
飞镖:
class MyComponent
{
Control ctrlRtc = new Control('test', rtcValidator);
static Map<String, bool> rtcValidator(Control control)
{
print(111);
}
}
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;
}
}
(未测试)
我认为您需要使用 ngFormControl
而不是 ngControl
。你不需要 #deviceRtc
间谍。
<input
type="number"
min="1"
max="43200"
style="text-align: center"
[(ngModel)]="device.rtc"
[ngFormControl]="ctrlRtc">
然后你会看到你的 rtcValidator(...)
每次输入改变时都会被调用。我不会费心解释验证器函数的 return 类型,因为 Günter 已经在他的回答中证明了这一点。
我没有尝试 运行 你的例子,但我有 a working example 你可以试试。