ERROR TypeError: Cannot read property 'email' of undefined

Hello, I’m facing Bizarre thing in ionic 3 app
I designed the UI in Ionic Creator
and download it,
I create a login page and there are some input fields, my problem is sometimes I’m getting an error and sometimes it works,

Error Messsage:

LoginPage.html:8 ERROR TypeError: Cannot read property 'email' of undefined
    at Object.eval [as updateDirectives] (LoginPage.html:9)
    at Object.debugUpdateDirectives [as updateDirectives] (core.js:14655)
    at checkAndUpdateView (core.js:13802)
    at callViewAction (core.js:14153)
    at execComponentViewsAction (core.js:14085)
    at checkAndUpdateView (core.js:13808)
    at callViewAction (core.js:14153)
    at execEmbeddedViewsAction (core.js:14111)
    at checkAndUpdateView (core.js:13803)
    at callViewAction (core.js:14153)
View_LoginPage_0 @ LoginPage.html:8


My Login HTML is :

  <div>
    <ion-list class="list" inset>
      <ion-item class="label">
        <ion-label color="mywhite" class="text-customise" floating>Email</ion-label>
        <ion-input color="mywhite" [(ngModel)]="user.email"></ion-input>
      </ion-item>

      <ion-item class="label">
        <ion-label type="text" color="mywhite" class="text-customise" floating>Password</ion-label>
        <ion-input type="password" color="mywhite" [(ngModel)]="user.password"></ion-input>
      </ion-item>
    </ion-list>
  </div>

  <p class="text text-customise" style="color:#ebebeb;">Forgot your password?</p>

  <div text-center>
    <button class="loginButtonWidth" ion-button color="mywhite" round (click)="login(user)">Login</button>
  </div>

and login.ts is :

  user:any = {};
  constructor(public navCtrl: NavController, public navParams: NavParams,public authService:AuthServiceProvider) {
  }

  ionViewCanEnter() {
    console.log('ionViewDidLoad LoginPage');
  }

  login(user:any){
    console.log(user);
    this.authService.loggedIn();
    this.navCtrl.setRoot(HomePage);
  }
  goSignupPage(){
    this.navCtrl.setRoot(SignupPage)
  }

its works when I just remove and again paste the line

user:any = {};
and sometimes it doesnot work,
can anyone tell me why it happen and how to solve it.
Thanks

Hello,

maybe user not always available at run time. Maybe you make a seperate email:string=’’: and fill it with user.email, when it is available.

Best regards, anna-liebt

In your login.ts try:

export interface User {
  email?: string;
  password?: string;
}

public user: User = new User;

See:

2 Likes

Or just in one line:
protected user:{email?:string,password?:string} = {};

instead of curly brace {}, use square brace of array []
user:any = [];