Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access a service from a custom validator in Angular2

I need to access my custom http service from inside a static method, as example:

import {Control} from 'angular2/common';
import {HttpService} from './http.service';

class UsernameValidator {
    static usernameExist(control: Control): Promise<ValidationResult> { 
        ... /* Access my HTTPservice here */
    }
}

How can I access a service in this case?

like image 868
Silencer Avatar asked Feb 19 '16 12:02

Silencer


People also ask

How do I add a custom validator to FormControl?

To validate required fields, for example, we can use the built-in required validator on template-driven forms by adding the required attribute. const control = new FormControl('', Validators. required); Those validators are very helpful because they allow us to perform standard form validation.

What are custom validators?

A validator in Angular is a function which returns null if a control is valid or an error object if it's invalid. For model-driven forms we create custom validation functions and pass them into the FormControl constructor.

Which form needs custom validator directive that wrap validation function for form validation?

Reactive forms define custom validators as functions that receive a control to validate. Template-driven forms are tied to template directives, and must provide custom validator directives that wrap validation functions.


2 Answers

Another approach consists in returning a function. This way this function can have access to HttpService instance provided during creation:

class UsernameValidator {
  static createUsernameExist(http:HttpService) {
    return (control: Control) => { 
      ... /* Access my HTTPservice here */
    }
  }
}

You can then use it like that:

validator: UsernameValidator.createUsernameExist(this.httpService)
like image 143
Thierry Templier Avatar answered Oct 16 '22 22:10

Thierry Templier


class UsernameValidator {
    constructor(http:HttpService){}

    usernameExist(control: Control): Promise<ValidationResult> { 
        ... /* Access my HTTPservice here */
    }
}

then use it like

validator: new UsernameValidator(http).usernameExist

The HttpService needs to be injected in the component constructor instead and then passed to the manually created validator instance as shown above.

like image 25
Günter Zöchbauer Avatar answered Oct 16 '22 22:10

Günter Zöchbauer