【问题标题】:Angular Material forms validation errorsAngular Material 表单验证错误
【发布时间】:2018-02-20 19:58:24
【问题描述】:

我有一个材料表格,里面有一个输入框:

<md-form-field class="input-full-width">
    <input mdInput class="form-control emp-info-input" type="text" placeholder="Description" formControlName="periodDesc">
    <md-error *ngIf="periodDesc.errors.required">This field is required</md-error>
</md-form-field>

表单生成器:

this.apprperiod = this.fb.group({
      'periodDesc' : new FormControl(this.periodDesc, [Validators.required,Validators.maxLength(50)])
    }, {validator: CustomValidator.validate});

加载时出现以下错误:

错误类型错误:无法读取未定义的属性“hasError”
在 Object.TestComponent._co [作为 updateDirectives] (test.html:33)
在 Object.debugUpdateDirectives [as updateDirectives] (core.es5.js:13075)
在 checkAndUpdateView (core.es5.js:12255)
在 callViewAction (core.es5.js:12620)
在 execComponentViewsAction (core.es5.js:12552)
在 checkAndUpdateView (core.es5.js:12261)
在 callViewAction (core.es5.js:12620)
在 execEmbeddedViewsAction (core.es5.js:12578)
在 checkAndUpdateView (core.es5.js:12256)
在 callViewAction (core.es5.js:12620)

【问题讨论】:

  • 这是因为加载时 field.errors 尚未设置。我用*ngIf="!periodDesc.valid" 解决了这个问题

标签: forms angular angular-material


【解决方案1】:

因为您必须像这样从表单中获取控件:

<md-error *ngIf="apprperiod.get('periodDesc').errors.required">This field is required</md-error>

或者

<md-error *ngIf="apprperiod.hasError('required', ['periodDesc'])">This field is required</md-error>

【讨论】:

    【解决方案2】:

    您可以在component 中创建方法来检查状态并验证FormGroup 中的字段:

    checkInvalidTouched(field: string) {
        return (
          !this.apprperiod.get(field).valid &&
          (this.apprperiod.get(field).touched || this.formulario.get(field).dirty)
        );
    }
    
    checkCustomValidator() {
        const formField = this.formulario.get('periodDesc');
        if (formField.errors) {
          return formField.errors['customValidator'] && checkValidTouched('periodDesc');
        }
    }
    

    然后将此方法用作*ngIf上的子句:

    <md-form-field class="input-full-width">
        <input mdInput class="form-control emp-info-input" type="text" placeholder="Description" formControlName="periodDesc">
        <md-error *ngIf="checkIfRequired('periodDesc')">This field is required.</md-error>
        <md-error *ngIf="checkCustomValidator('periodDesc')">Custom validator return error.</md-error>
    </md-form-field>
    

    【讨论】:

      猜你喜欢
      • 2016-07-26
      • 2018-02-22
      • 2016-09-19
      • 1970-01-01
      • 2015-08-22
      • 1970-01-01
      • 2015-09-19
      • 2021-02-01
      • 2019-04-08
      相关资源
      最近更新 更多