首页 > 解决方案 > Angular Reactive Forms 使用插值在输入上动态生成验证属性

问题描述

在我看来,使用插值在输入上动态生成验证属性中引发了完全相同的问题,但是我正在寻找解决方案Angular,而不是AngularJS.

在我的反应式表单中,我使用了这样的验证器:

public contactForm: FormGroup = this.formBuilder.group({
  ...
  formControlDescription: [
    '',
    Validators.compose([
      Validators.maxLength(5000),
      Validators.minLength(30),
      Validators.required,
    ]),
  ],
  ...
});

html我以5000这种方式对数字进行硬编码:

<mat-hint align="end">{{ contactForm.get('formControlDescription')!.value.length }} / 5000</mat-hint>

问题:有没有办法动态访问contactForm's中的formControlDescription's ?Validators.maxLength(5000)html

标签: angulartypescriptangular-reactive-formsreactive-formsangular-validation

解决方案


您可以从最小/最大验证器中获取错误对象,如下所示:

<mat-hint align="end">{{ contactForm.get('formControlDescription')?.errors.maxlength?.actualLength }} / {{ contactForm.get('formControlDescription')?.errors.maxlength?.requiredLength }} </mat-hint>

更清洁的版本:

<mat-hint align="end">    
  {{ contactForm.errors?.formControlDescription?.maxlength?.actualLength}} / 
  {{ contactForm.errors?.formControlDescription?.maxlength?.requiredLength}}
</mat-hint>

关于maxLength Validator的官方文档

更新

只有当验证器被触发并呈现为无效时,角度验证器的值才会对您可用。

例如,如果你有minLength(10),它会在你被触摸的那一刻给你无效的输入,直到字符达到或超过 10 个。对于maxLength(20),它只会在errors触发后在对象中可用,即用户输入的字符超过 20 个。

如果您打算使用actualLengthrequiredLength一致地向用户显示统计信息,则会出现问题,因为它们只会在其中一个minLengthmaxLength无效时出现。

如前所述,对您来说最好的方法是使用单独的变量来设置和显示所需的长度。例如:

const validatorOptions = {
  maxLength: 5000,
  minLength: 5
}

然后在您的模板中使用它:

<mat-hint align="end">{{ contactForm.controls.formControlDescription?.value.length }} / {{validatorOptions.maxLength}}</mat-hint>

推荐阅读