A_Singh A_Singh - 6 months ago 37
TypeScript Question

How to implement Async Validator in Angular2

1. Is it even supported by Angular yet ? see this open issue

2. If it is, then what is wrong in the code below

export class someClass{


constructor(public http:Http, public formBuilder:FormBuilder)
this.myForm = formBuilder.group({
ImageId: ["", Validators.required, this.asynValidator]

asyncValidator(control: Control): {[key: string]: any} {

return new Promise (resolve => {

let headers = new Headers();
headers.append('Content-Type', 'application/json');

this.http.get('http://localhost/ImageIdValidate?id='+ control.value, {headers:headers})
.map(res => res.json())
.subscribe(data => {
if(data != null) {
resolve({"duplicate": true})
else resolve(null);

It doesn't even make a server request.


You need to bind your method on the component instance itself as described below:

this.myForm = formBuilder.group({
            ImageId: ["",    

Otherwise you won't be able to use the http property to execute your request.

This article could also give you some hints about asynchronous form validation (see the section "asynchronous validation"):