如何将参数传递到异步验证器以进行反应角控制



问题,

我正在使用相同的组件进行阅读/编辑例程。async-validator与新条目完美搭配。如果用户意外更改值并试图恢复为保存的值,则问题开始。我当前的代码将运行不管,并返回现有的值。我想通过控制值传递更多数据,以便我可以验证该对值是否已经存在。

我正在发布相关代码

这是我的form control

patientEmail: new FormControl(
    null,
    [Validators.email, Validators.required],
    FormControlValidator.createEmailAsyncValidator(
      this.asyncValidatorService
    ),
  ),

我的异步验证器创建器类是

export class FormControlValidator {
  static createEmailAsyncValidator(asyncValidatorService: AsyncValidationService) {
    return (control: AbstractControl) => {
      if (!control.pristine) {
        control.markAsPristine();
        return asyncValidatorService
          .validateEmailNotTaken(control)
          .map((response: HttpResponse<boolean>) => {
            return !response.body ? null : { taken: true };
          });
      }
      return Observable.of(null);
    };
  }

最后我的服务,

@Injectable()
export class AsyncValidationService {
  constructor(private httpService: HttpClientService) {}
  public validateEmailNotTaken(control: AbstractControl) {
    return this.httpService.getRequest(
      'PatientsRegistration/IsPatientEmailExist?email=' + control.value,
    );
  }
}

我希望能够将另一个参数传递给我的createEmailAsyncValidator,如果可能

如果您需要基于另一个控件验证控件,则需要将验证器提升为父控件。这是验证器的一个示例,该示例检查电子邮件是否以人的名称开头(另一个控制值(。

app.component.ts

import { Component } from '@angular/core';
import {FormBuilder, FormControl, FormGroup, ValidatorFn} from '@angular/forms'
const personalEmailValidator: ValidatorFn = (ctrl: FormGroup) => {
  const email = ctrl.get('email') as FormControl;
  const name = ctrl.get('name') as FormControl;
  const valid = (email.value || '').startsWith(name.value);
  return valid ? null : { personalEmailError: 'Email must start with a person name'}
}
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  form: FormGroup;
  constructor(private fb: FormBuilder) {
    this.form = this.fb.group({
      email: [null],
      name: [null]
    }, { validator: personalEmailValidator })
  }
}

app.component.html

<input [formControl]="form.get('name')" placeholder="name" />
<input [formControl]="form.get('email')" placeholder="email" />
{{ form.hasError('personalEmailError') ? form.getError('personalEmailError') : 'form is valid'}}

实时演示

所以我以另一种方式进行了工作,受托马斯·库拉(Tomasz Kula(的启发

我创建了一个实现AsyncValidator接口的异步Directive,我将额外的参数作为"对象,就我而言,

{
 coupledControl: AbstractControl,
 method: {
          apiUrl: string
         }
} 

这是我的directive代码,

import { Directive, forwardRef, Input } from '@angular/core';
import { NG_ASYNC_VALIDATORS, Validator, AbstractControl } from '@angular/forms';
import { Observable } from 'rxjs/Observable';
import { HttpClientService } from '../../../../../shared/services/httpclient.service';
import { HttpResponse } from '@angular/common/http';
import { IAsyncMethod } from './../interfaces/async-methods-interface';

@Directive({
  // tslint:disable-next-line:directive-selector
  selector: '[asyncValidator][formControlName], [asyncValidator][ngModel]',
  providers: [
    {
      provide: NG_ASYNC_VALIDATORS,
      useExisting: forwardRef(() => AsynValidatorDirective),
      multi: true,
    },
  ],
})
export class AsynValidatorDirective implements Validator {
  @Input() asyncValidator: { coupledControl: AbstractControl; method: IAsyncMethod };
  validate(
    control: AbstractControl,
  ): Promise<{ [key: string]: any }> | Observable<{ [key: string]: any }> {
    return this.validateIsExistAsync(control);
  }
  constructor(private httpService: HttpClientService) {}
  validateIsExistAsync(control: AbstractControl) {
    if (!control.pristine) {
      const coupledControl: AbstractControl = this.asyncValidator.coupledControl;
      const method: IAsyncMethod = this.asyncValidator.method;
      return this.httpService
        .getRequest(method.apiUrl + '?control=' + control.value + '&id=' + coupledControl.value)
        .map((response: HttpResponse<boolean>) => {
          return !response.body ? null : { asyncInvalid: true };
        });
    }
    return Observable.of(null);
  }
}

在我的HTML中,

 <input [asyncValidator]="{coupledControl: patientRestrationForm.get('patientFileId'), method: this.asyncMethods.validatePatientEmail }" [errorStateMatcher]="matcher" matInput autocomplete="off" formControlName="patientEmail">

,在我的后端,我检查两者都存在并匹配,简单逻辑!

会感谢任何输入,

最新更新