如何读取maxLength验证程序的值,以便可以将其打印到表单中? [英] How do you read the value of a maxLength validator so that you can print it into the form?

查看:50
本文介绍了如何读取maxLength验证程序的值,以便可以将其打印到表单中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个反应式,它使用验证器来控制输入的长度.

I have a reactive form which uses a validator to control the length of the input.

我想在模板中再次读取该长度,以便可以指导用户实际最大长度是多少,但是我不知道如何从表单中读取该长度.

I would like to read that length back again in the template so that I can guide the user as to what the maximum length actually is but I can't figure out how to read it from the form.

有可能吗?

// investor-signup.component.ts
export class InvestorSignupComponent implements OnInit {

  public investorForm = this.fb.group({
    name: ['', [Validators.required, Validators.maxLength(5)]],
    // I want to access be able be able to print the '5' above into the form 
    // without having to duplicate the value or create another variable.
    url: [''],
    type: [''],
  })
}

// investor-signup.component.html

...
<input matInput
        formControlName="name"
        required
        placeholder="Startup Capital Inc.">

<mat-hint>Must be less than {{investorForm.name.validators.maxLength.value}} characters long</mat-hint>
// note - the investorForm.name.validators.maxLength.value above does NOT work

从FormControl对象中读取此maxLength的正确方法是什么?

What is the correct way to read this maxLength back out of the FormControl object?

[为清晰起见,进行编辑]我想在用户创建错误之前 读取值,而不是之后.这是为了告诉他们他们的津贴额是多少,而不是告诉他们有问题.

[edit for clarity] I want to read the value out before the user has created the error, not afterwards. This is for telling them what their allowance is rather than that they have an issue.

我也想避免使用单独的变量,以使代码最少.

I'd also like to avoid using a separate variable in order to keep code minimal.

推荐答案

应该是这样的:

 <mat-hint *ngIf="investorForm.hasError('maxlength', 'name')">
  Max length: {{ investorForm.get('name').errors.maxlength.requiredLength }}</mat-hint>

您必须通过硬编码或从常量文件中设置 maxLength 的值.您可以将限制存储到变量中,然后在视图中使用.即:

You must be setting the value of maxLength either hard coded or from a constant file. you can store the limit into a variable and then use in the view. i.e :

component.ts 中:

const MAX_LENGTH = 3;

testForm: FormGroup;
  private maxLen = MAX_LENGTH;
  constructor(private fb: FormBuilder) { }

  ngOnInit() {
    this.testForm = this.fb.group({
      name: ['', [Validators.maxLength(this.maxLen)]],
    })
  }

component.html 中:;

<small> max allowed length is :  {{maxLen}} </small>

演示

这篇关于如何读取maxLength验证程序的值,以便可以将其打印到表单中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆