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.
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"):
as of newer versions of Angular, but pre version 5.0.0
you would add the async validator as the third argument for your formcontrol:
myControl: ['', [Validators.required], [this.asyncValidator.bind(this)]]
since version 5.0.0
you can now mark the validators like so:
myControl: ['', {validators: [Validators.required], asyncValidators:[this.asyncValidator.bind(this)]}]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With