【问题标题】:How to get form control validation errors in template in Angular如何在Angular中的模板中获取表单控件验证错误
【发布时间】:2017-12-13 08:50:03
【问题描述】:

我有一个表单,它根据下拉列表中的某个值更改其验证。如果选择大学 A,则要求最低百分比为 60,如果选择大学 B,则最低百分比降至 55。 尽管我已经找到了一种方法来获取模板中的最小错误,这样我就不必在模板中对百分比值进行硬编码。虽然我不确定这是否正确。

<div formGroupName="marks">
  <div class="form-group">
    <label for="email" class="col-lg-3 control-label">Semester 1</label>
    <div class="col-lg-3">
      <input autocomplete="off"
             #sem1
             type="text"
             min="0"
             max="99"
             maxlength="1"
             maxlength="2"
             class="form-control"
             id="email"
             placeholder="Sem 1 (%)"
             (keypress)="onlyNumberKey($event)"
             formControlName="sem1">
      <span *ngIf="registrationForm.controls['marks'].controls['sem1'].hasError('required') &&
                   registrationForm.controls['marks'].controls['sem1'].touched"
                   class="text-danger">
        Sem 1 percentage required
      </span>
      <span *ngIf="registrationForm.controls['marks'].controls['sem1'].hasError('min') ||
                   registrationForm.controls['marks'].controls['sem1'].hasError('max') ||
                   registrationForm.controls['marks'].controls['sem1'].hasError('minlength')||
                   registrationForm.controls['marks'].controls['sem1'].hasError('maxlength') &&
                   registrationForm.controls['marks'].controls['sem1'].touched"
                   class="text-danger">
        Percenatge must be {{ registrationForm.get('marks.sem1')._errors.min.min }}  and above.
      </span>
    </div>
  </div>
</div>

组件

registrationForm = new FormGroup({
  college: new FormControl('', [
    Validators.required, dropDrownValidator
  ]),
  marks: new FormGroup({
    sem1: new FormControl('',
      [
        Validators.required,
        Validators.min(60),
        Validators.max(99),
        Validators.minLength(1),
        Validators.maxLength(2)
      ]
    )
  })
});

【问题讨论】:

    标签: angular angular2-forms angular-reactive-forms


    【解决方案1】:

    要实现你想要的,你必须观察你的college控件中的变化。

    您可以在模板中使用(change)

    <select formControlName="college" (change)="handleChange($event.target.value)">
      ...
    </select>
    

    甚至在组件中使用valueChanges

    this.registrationForm.get('college').valueChanges.subscribe(college => this.handleChange(college));
    

    在您的function 中,根据college 用户的选择,您可以使用AbstractControl#setValidators + AbstractControl#updateValueAndValidity(申请)将最小值设置为您的验证器,如下所示:

    handleChange(selectedCollege: string): void {
      const min = selectedCollege === 'CollegeA' ? 60 : 55;
      const control = this.registrationForm.get('marks.sem1');
      control.setValidators([Validators.required, customMin(min)]);
      control.updateValueAndValidity();
    }
    

    提示:

    1 - 由于您使用的是模型驱动表单,因此您不应该在 HTML 中放置验证,保持干净并将所有内容放在组件中。

    2 - 您可以使用FormBuilder 来简化form 的构造(参见底部的演示)。

    3 - 你不应该像这样访问私有属性:

    {{ registrationForm.get('marks.sem1')._errors.min.min }}
    

    如果需要,只需使用 errors 而不是 _errors

    4 - 您可以进一步简化标记:

    代替:

    <span *ngIf="registrationForm.controls['marks'].controls['sem1'].hasError('required') &&
                 registrationForm.controls['marks'].controls['sem1'].touched" 
                 class="text-danger">
      Sem 1 percentage required
    </span>
    <span *ngIf="registrationForm.controls['marks'].controls['sem1'].hasError('min') ||
                 registrationForm.controls['marks'].controls['sem1'].hasError('max') ||
                 registrationForm.controls['marks'].controls['sem1'].hasError('minlength')||
                 registrationForm.controls['marks'].controls['sem1'].hasError('maxlength') &&
                 registrationForm.controls['marks'].controls['sem1'].touched"
                 class="text-danger">
      Percenatge must be {{ registrationForm.get('marks.sem1')._errors.min.min }}  and above.
    </span>
    

    你可以拥有:

    <div class="text-danger" *ngIf="registrationForm.get('marks.sem1').touched">
      <span *ngIf="registrationForm.hasError('required', 'marks.sem1')">
        Sem 1 percentage required
      </span>
      <span *ngIf="registrationForm.getError('customMin', 'marks.sem1') as error">
        Percentage must be greater than or equal to {{ error.min }}.
      </span>
    </div>
    

    WORKING DEMO

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-19
      • 2018-04-28
      • 1970-01-01
      • 1970-01-01
      • 2021-02-11
      • 2017-07-16
      • 2021-04-10
      • 1970-01-01
      相关资源
      最近更新 更多