4

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)

1
  • This is cause field.errors is not set yet, when loading. I solved this with *ngIf="!periodDesc.valid" Commented Sep 12, 2017 at 11:34

2 Answers 2

3

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>
Sign up to request clarification or add additional context in comments.

Comments

1

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.