简体   繁体   中英

Angular async reactive form Validation

I have been looking lots of tutorials to could implement async validators to a reactive form in angular but I always get an error.

What I need to do, is to check a value written in a field exists in an array of objects stored in a service.

The problem is that the validator works fine when I do the comparison to a fixed value, but when I try to use the service it says that the service is undefined.

Code for the form:

ngOnInit() {
 this.FormNuevaConf =this.fb.group({
  'codigo': [null,null],
  'valor': [null,null,this.valorUnicoValidator]
})}

Code for the validator:

valorUnicoValidator (control: AbstractControl, service:UnidadesService): Promise<ValidationErrors | null> | Observable<ValidationErrors | null> {
return of(service.subscribe(control) === control.value).pipe(
  map(result => result ? { invalid: true } : null)
  );}

subscribe(control) is a function in the service that returns a value if the control.value is found in the array of objects returned from the db query.

I haven't found a clear explanation of how to build an async validator if you have one you can recommend me I will thank that.

The service cannot be injected in the validator, you have to inject it as private in the constructor of your component class and then use it in the validator since you will have access to it.

Something like:

constructor(private service: UnidadesService) {}

ngOnInit() {
  this.FormNuevaConf =this.fb.group({
    'codigo': [null,null],
    'valor': [null,null,this.valorUnicoValidator]
  })
}

valorUnicoValidator (control: AbstractControl): Promise<ValidationErrors | null> | Observable<ValidationErrors | null> {
    return of(this.service.subscribe(control) === control.value).pipe(
      map(result => result ? { invalid: true } : null)
);}

You can make a validator builder like this if your component has a copy of the service instance that you want.

myValidator.validator.ts:

export function MyValidator(service: MyService) {
    return (control: AbstractControl): { [key: string]: any } | null => {
        if (service.getValue()) {
            return { Error: true };
        } else {
            return null;
        }
    };
}

in your component:

this.noteForm.addControl("MyFormContorl", new FormControl(null,
            [Validators.required, MyValidator(this.myService)])); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM