A_Singh A_Singh - 1 month ago 14
TypeScript Question

How to implement Custom 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{

myForm:ControlGroup;

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 => {
console.log(data);
if(data != null) {
resolve({"duplicate": true})
}
else resolve(null);
})
});
});
}
}


It doesn't even make a server request.

Answer

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

this.myForm = formBuilder.group({
            ImageId: ["",    
               Validators.required, 
               this.asynValidator.bind(this)]
    });

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"):

Comments