1

我正在使用 Ionic 2 开发应用程序并遇到错误。当我删除 [(ngModel)]="register.username" 错误正在消失。

TypeError: Cannot read property 'username' of undefined in [register.username in RegisterPage@15:19]
<ion-navbar *navbar>
  <ion-title>Register</ion-title>
</ion-navbar>

<ion-content class="login-page">

  <ion-list>
    <div class="logo">
      <img src="img/appicon.svg">
    </div>

    <form #signupForm="ngForm" novalidate>
      <ion-item>
        <ion-label floating primary>Username</ion-label>
        <ion-input [(ngModel)]="register.username" ngControl="username" type="text" #username="ngForm" required>
        </ion-input>
      </ion-item>
      <p [hidden]="username.valid || submitted == false" danger padding-left>
        Username is required
      </p>

      <ion-item>
        <ion-label floating primary>Password</ion-label>
        <ion-input [(ngModel)]="register.password" ngControl="password" type="password" #password="ngForm" required>
        </ion-input>
      </ion-item>
      <p [hidden]="password.valid || submitted == false" danger padding-left>
        Password is required
      </p>

      <div padding>
        <button (click)="onSignup(signupForm)" type="submit" primary block>Create</button>
      </div>
    </form>
  </ion-list>

</ion-content>

注册.js

import { App, Page, NavController } from 'ionic/ionic';
@Page({
  templateUrl: 'build/pages/register/register.html'
})

export class RegisterPage {
  constructor(nav: NavController) {
    this.nav = nav;
  }

  onSignup(form) {
    // console.log(form);
    // if (form.valid) {
    //   this.nav.push();
    // }
  }
}

想知道我做错了什么吗?我应该阅读任何文件吗?(如果您想了解更多信息,请告诉我)

4

1 回答 1

1

也许您的register对象是异步加载的。为了防止这种情况,只需使用 Elvis 运算符:register?.usernamengIf在您的表单周围使用:

<form #signupForm="ngForm" novalidate *ngIf="register">
  <ion-item>
    <ion-label floating primary>Username</ion-label>
    <ion-input [(ngModel)]="register.username"
               ngControl="username" type="text"
               #username="ngForm" required>
    </ion-input>
  </ion-item>
  (...)
</form>

编辑

register对象设置为空对象应该解决您的问题:

import { App, Page, NavController } from 'ionic/ionic';
@Page({
  templateUrl: 'build/pages/register/register.html'
})

export class RegisterPage {
  constructor(nav: NavController) {
    this.nav = nav;
    this.register = {};
  }

  onSignup(form) {
    // console.log(form);
    // if (form.valid) {
    //   this.nav.push();
    // }
  }
}

希望它可以帮助你,蒂埃里

于 2016-01-31T09:37:02.543 回答