Inject custom service into a custom Validator

前端 未结 1 1994
鱼传尺愫
鱼传尺愫 2021-02-03 11:19

I\'m trying to make a custom Angular 2 form Validator to check if a user exist on a data base.

This is the code of my custom form Validator

1条回答
  •  醉梦人生
    2021-02-03 12:14

    @Injectable()
    export class EmailValidator {
    
      constructor(private api:API) {}
    
      /* static */ checkEmail(control: FormControl,): any {
        return this.api.checkUser(control.value).then(response => {
          response;
        });
      }
    }
    

    Add it to of @NgModule() or @Component() depending on what scope you want it to have

    providers: [EmailValidator]
    

    Inject it to the component where you want to use it

    export class MyComponent {
      constructor(private emailValidator:EmailValidator, fb:FormBuilder){}
    
      this myForm = fb.group({
        email: [], [this.emailValidator.checkEmail.bind(this.emailValidator)]
      });
    }
    

    0 讨论(0)
提交回复
热议问题