Angular Material forms validation errors

2019-06-08 12:57发布

I have a material form in which I have an input box:

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

Formbuilder:

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

I get the following error while loading:

ERROR TypeError: Cannot read property 'hasError' of undefined
at Object.TestComponent._co [as updateDirectives] (test.html:33)
at Object.debugUpdateDirectives [as updateDirectives] (core.es5.js:13075)
at checkAndUpdateView (core.es5.js:12255)
at callViewAction (core.es5.js:12620)
at execComponentViewsAction (core.es5.js:12552)
at checkAndUpdateView (core.es5.js:12261)
at callViewAction (core.es5.js:12620)
at execEmbeddedViewsAction (core.es5.js:12578)
at checkAndUpdateView (core.es5.js:12256)
at callViewAction (core.es5.js:12620)

2条回答
叼着烟拽天下
2楼-- · 2019-06-08 13:39

You can create the methods in your component to check state and validation a field in 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');
    }
}

Then use this method as clause on *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>
查看更多
smile是对你的礼貌
3楼-- · 2019-06-08 13:55

Because you have to get the control from the form like this :

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

Or

<md-error *ngIf="apprperiod.hasError('required', ['periodDesc'])">This field is required</md-error>
查看更多
登录 后发表回答