我为我的模板驱动表单创建了一个异步验证器。
import {Directive, forwardRef} from "@angular/core";
import {NG_ASYNC_VALIDATORS, Validator, AbstractControl, AsyncValidator} from "@angular/forms";
import {Observable} from "rxjs";
@Directive({
selector: '[asyncValidator][ngModel]',
providers: [{
provide: NG_ASYNC_VALIDATORS, useExisting: forwardRef(() => AsyncAgeValidator), multi: true
}]
})
export class AsyncAgeValidator implements Validator{
validate(c: AbstractControl): Observable<{[key : number] : any}>{
return this.validateAgeObservable(c.value);
}
validateAgeObservable( age: number ) {
return new Observable(observer => {
if( age === 20 ) {
observer.next(null);
} else {
observer.next({asyncInvalid: true});
console.log('validate');
}
});
}
}
}
我在我的模板中使用它,如下所示,但我没有从模板中的验证器获得我期望的错误消息。该调用将发送给验证器,但我猜它没有在组件中注册可观察对象。
<md-input-container>
<input mdInput type="number" name="age" [(ngModel)]="user.age" placeholder="Age" required asyncValidator>
</md-input-container>