我写了一个自定义的验证指令那样:不叫Angular2自定义验证
const DURATION_VALIDATOR = new Provider(
NG_VALIDATORS,
{useExisting: forwardRef(() => DurationDirective), multi: true}
);
@Directive({
selector: '[ngModel][duration], [formControl][duration]',
providers: [{
provide: NG_VALIDATORS,
useExisting: forwardRef(() => DurationDirective),
multi: true }]
})
export class DurationDirective implements Validator{
constructor(public model:NgModel){
console.error('init')
}
validate(c:FormControl) {
console.error('validate')
return {'err...':'err...'};
}
}
我的HTML看起来像这样:
<input
type="text"
[(ngModel)]="preparation.duration"
duration
required
>
我的问题是,虽然验证被初始化,即' init'被记录到控制台,验证函数永远不会被调用,即在输入字段中输入时,“验证”从不记录到控制台。由于验证程序已初始化,因此我假设我“正确”连接了所有内容。那么缺少什么?
我已将disableDeprecatedForms(),provideForms()添加到我的组件提供程序属性中。但这似乎没有任何影响。你能解释为什么吗?这是我更新的plunk https://plnkr.co/edit/ztuBIZc3QMRwMg62scZR?p=preview – schacki
这个plunk仍然没有在bootstrap()调用中提供两个调用。将您在提供者属性中的两个调用移动到引导方法可以解决问题。 https://plnkr.co/edit/b2PipR?p=preview – batesiiic
对不起,这是一个误解。我故意将提供的调用从引导方法转移到my-app组件来说明我的问题:我的假设是将2个调用添加到组件提供程序中就足够了。你能解释为什么不能? – schacki