A_Singh A_Singh - 1 year ago 148
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{


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.

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download