user6579134
user6579134

Reputation: 839

angular2 forms error - Cannot read property 'hasError' of undefined

I'm creating a user registration for with ionic2 which contains a password field which is set to have a minimum length 10. When the characters is not up to 10 i'd like to show the user as the user types but i get this error on the page

Cannot read property 'hasError' of undefined

HTML

<ion-item>
          <ion-label>Password</ion-label>
          <ion-input type="number" formControlName="Password"  [(ngModel)]="Password"></ion-input>
          <div *ngIf = "Password.hasError('minlength') && !Password.hasError('required')" class = "alert alert-danger">
            <span>Password should contain 10 characters</span>
          </div>  
        </ion-item>

JS

this.registerForm = this.formBuilder.group({
                  username: [''],
                  password: ['', [Validators.required, Validators.minLength(8)]],
                });

Upvotes: 1

Views: 2324

Answers (2)

Tomasz Kula
Tomasz Kula

Reputation: 16857

Do not mix Reactive and Template Driven forms. Complete example with Reactive Forms only:

component.html

<form [formGroup]="registerForm">
  <ion-item>
    <ion-label>Password</ion-label>
    <ion-input type="number" formControlName="password"></ion-input>
     <div *ngIf = "passwordCtrl.hasError('minlength') && passwordCtrl.hasError('required')" class = "alert alert-danger">
       <span>Password should contain 10 characters</span>
     </div>  
 </ion-item>
</form>

component.ts

this.registerForm = this.formBuilder.group({
  username: [''],
  password: ['', [Validators.required, Validators.minLength(8)]],
});

get passwordCtrl() {
  return this.registerForm.get('password');
}

Upvotes: 1

Suren Srapyan
Suren Srapyan

Reputation: 68685

You can't just use Password to access the form control. You need to use

registerForm.controls.password.hasError()

One more note.

You have mixed two approaches - Template driven forms and Reactive forms. You have already used reactive forms, so remove ngModel part and let only formControlName with lowercase variant for password.

<ion-input type="number" formControlName="password"></ion-input>

and you can provide value for that control just using

registerForm.patchValues({
   password: "*****"
})

Upvotes: 0

Related Questions