In Angular 2 I am trying to create my own custom Validator.
I have created my own CustomValidators class, which implements the validator interface.
import { FormControl } from "@angular/forms";
import { MyhttpService } from "./myhttp.service";
import { Response } from "@angular/http";
import { Injectable, Directive } from '@angular/core';
@Injectable()
export class CustomValidators{
constructor(private _http : MyhttpService){
}
public api(c : FormControl)
{
// Run
this._http.get("/expenses/email?email=" + c.value).subscribe((res:Response) => {
if(res.status === 200){
// email exists
return null;
} else {
return {"email" : true}
}
});
}
If I make api a static method, then I can use the class successfully using.
this._formDetails = fb.group({
"managerEmail" : ["", [Validators.required, CustomValidators.api] ]
});
However of course this is a static method so I don't have access to any of the constructor values as the constructor has not been run.
Therefore I cannot find a way of implementing custom validator with dependencies, there must be a way.
I have tried listing CustomValidators as a provider so my class receives an instantiated object of the class.
Property 'api' does not exist on type 'typeof CustomValidators'
Am I providing the class in the correct way? Why does the method not exist?