我想为输入文本创建自定义组件,但我不知道如何将每个输入字段的验证绑定到自定义组件.有没有办法将每个字段的误差设置为如下所示的对象数组

<app-custom-input
          formControlName="username"
          label="Username"
          [errors]="[
          { type: 'required', message: 'is required' },
          { type: 'minlength', message: 'min length error' }
        ]"
        ></app-custom-input>

事实上,我想编写具有不同验证的可重用组件,例如,一个字段是必填的,而另一个字段具有长度条件.

stackblitz.io

推荐答案

循序渐进.

当我们使用VALIDATE创建自定义表单控件时,函数VALIDATE应该返回或返回一个对象,或者返回空(如果没有错误).

  public validate(c: FormControl) {
    const errors: any[] = [];
    if (!this.control) this.control = c;

    this.errors &&
      this.errors.forEach((error) => {
        if (error.type == 'required') {
          if (!c.value) {
            errors.push({ required: true, message: error.message });
          }
        }
      });
    return errors.length ? { error: errors } : null;
  }

请参见返回一个具有唯一属性"Error"的对象,该属性是一个错误array.

这个错误是内部控件的错误not--您在定制输入中输入--否则就是"Parent"中声明的FormControl.因此,要在自定义表单控件内迭代此错误,我们需要"获取它".

通常,您可以使用构造函数

constructor(@Optional() @Self() public ngControl: NgControl){
  if (this.ngControl != null) {
     this.ngControl.valueAccessor = this;
  }
}

但是,由于我们只需声明一个验证函数,并在验证函数中为其赋值

  control!: AbstractControl;

  public validate(c: FormControl) {
    if (!this.control) this.control = c;
    ...rest of the code..
  }

最后一种方法是迭代此错误

<ng-container *ngIf="control?.touched || control?.dirty">
  <ng-container *ngFor="let error of control?.errors?.error">
    <div class="error-text">
      {{ error.message }}
    </div>
  </ng-container>
</ng-container>

你的forked stackblitz

注意:请注意,您不必将validators加到您的FormControls

在您的代码中:

registrationForm = this.fb.group({
    username: [''],
    password: [''],
  });

update只在需要时才发送,我们需要使用类似于

  public validate(c: FormControl) {
    const errors: any[] = [];
    if (!this.control) this.control = c;
cons errorRequired==!c.value && this.errors?this.errors.find(x=>x=='required'):null
 if (errorRequired)
     return [{required:true,message:errorRequired.message}]
    
    this.errors &&
      this.errors.forEach((error) => {
        if (error.type == 'required') {
          if (!c.value) {
            errors.push({ required: true, message: error.message });
          }
        }
      });
    return errors.length ? { error: errors } : null;

Angular相关问答推荐

根据Angular中的构建来卸载独立组件

如何在@angular/material-experimental中使用自定义调色板-Expeded $connect.Color.primary将成为有效的M3调色板

无效的ICU消息.缺少';}';|Angular material 拖放(&A)

一个接一个的Angular http请求,但只关心第一个

如何修复不允许的HttpErrorResponse 405?

Router.navigate() 在功能拦截器内不起作用

Angular 15 Ref 错误:初始化前无法访问组件 A

http 调用的 RxJs 数组

RxJs 中的空闲可观察对象在幕后做了什么?

将 injectiontoken 用于 Angular 中的模块特定设置

如何禁用特定数据集图表js的默认标签

Angular 项目构建仅在 GitHub Actions 上失败

如何为所有模块全局声明指令?

Angular2 CLI 错误@angular/compiler-cli包未正确安装

Angular 2 - 什么是Root Scope?

ViewChild 和 ContentChild 的所有有效 Select 器是什么?

ERROR 错误:StaticInjectorError(AppModule)[UserformService -> HttpClient]:

Angular 4 错误:没有 HttpClient 的provider提供者

ng build 时超出调用重试次数异常

在 Angular 2 中对 observable 进行单元测试