【问题标题】:Angular Reactive Forms Dynamically Generating Validation Attribute on Input using InterpolationAngular Reactive Forms 使用插值在输入上动态生成验证属性
【发布时间】:2021-02-20 13:29:14
【问题描述】:

在我看来,Dynamically generating validation attribute on input using interpolation 中提出的问题完全相同,但我正在寻找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>

问题:有没有办法动态访问html中的contactFormformControlDescriptionValidators.maxLength(5000)

【问题讨论】:

  • 您首先从哪里获得 5000 值?
  • html?它是硬编码的。

标签: angular typescript angular-reactive-forms reactive-forms angular-validation


【解决方案1】:

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

<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>

【讨论】:

  • 那不是我。我没有投反对票,实际上我投了赞成票。很快就会检查出来,如果有效,我会接受答案:)
  • 感谢@DanielDanielecki,有人在没有提及任何理由的情况下投了反对票,我看不出答案有什么问题。你能试试我的建议吗?如果出现任何问题,请发表评论
  • 现在得到它的错误,我创建了一个公共变量,它暴露给html以及传递给maxLenght(和minLength) - 就像在@ 987654322@。您能否使用这些 cmets 中提到的信息更新您的答案?然后我会接受它。
  • 看看丹尼尔
  • 已接受 :) 顺便说一句:我为每个验证器创建了一个单独的变量,但这只是一件小事。首选在变量的type 中表达,即number
猜你喜欢
  • 1970-01-01
  • 2020-12-30
  • 2023-03-04
  • 1970-01-01
  • 2018-07-06
  • 2017-03-10
  • 1970-01-01
  • 2021-04-28
  • 1970-01-01
相关资源
最近更新 更多