Cannot read property 'hasError' of null


#1

I was following the example here for angular Form validation:

and I got the same error in the two examples:

Cannot read property ‘hasError’ of null

my AddWork.html is:

 <form novalidate [formGroup]="AddWorkForm" (ngSubmit)="addworksdata()">
    <ion-list>
      <ion-item>
        <ion-label floating> Work Title</ion-label>
        <ion-input formControlName="workname"  [(ngModel)]="worksdata.workName" type="text" ></ion-input>
      </ion-item>
      <ion-item *ngFor="let validation of validation_messages.Workname">
        <div *ngIf="AddWorkForm.get('workname').hasError(validation.type)" >
          <p>{{validation.message}}</p>
        </div>
      </ion-item>
      <ion-item>
        <ion-label floating>Work ID</ion-label>
        <ion-input  formControlName="workclass" [(ngModel)]="worksdata.workClass" type="text" ></ion-input>
      </ion-item>
      <ion-item>
        <button type="submit" ion-button full [disabled]="!AddWorkForm.valid" >Save Work</button>
      </ion-item>
    </ion-list>
  </form>

and my AddWork.ts is:

import { FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms';




@IonicPage()
@Component({
  selector: 'page-add-work',
  templateUrl: 'add-work.html',
})
export class AddWorkPage {
  public AddWorkForm:FormGroup;
workers: any = [];
  worksdata={
    workName:'',
    workersNames:"",
    workClass:'',
  };
  validation_messages={
    'Workname':[
      { type: 'required', message: 'this input is required' },
      { type: 'minLength', message: 'Please enter at least 3 letters.' },
      { type: 'maxLength', message: 'you can use only 25 letters.'' }
    ],
    'Workclass':[
      { type: 'required', message: 'this input is required ' },
      { type: 'minLength', message: 'Please enter at least 3 letters.' },
      { type: 'maxLength', message: 'you can use only 10 letters.' },
      { type: 'pattern', message: 'You can use only English letters' }
    ]
  };
constructor(
public FormBuilder:FormBuilder
){
this.AddWorkForm =this.FormBuilder.group({
        Workname:['',Validators.required,Validators.minLength(3),Validators.maxLength(25)],
          Workclass:['',Validators.required,Validators.pattern('[a-zA-Z]*'),Validators.minLength(3),Validators.maxLength(10)]
      });
}

}

My ionic version is ionic 3 with angular 5


#2

See: A good form validation example?

Some sample code: https://github.com/Robinyo/big-top


#3

Never do this. Pick one or the other, but don’t have both formControlName and [(ngModel)]. You will immediately descend into a rabbit hole of confusing error messages about values changing after they have been checked.


#5

I removed the ngModel and I’m still getting the same error!