Ionic 2 get ion-input value

2019-07-18 02:56发布

I am creating a login with ionic 2. Please don't just answer "you just need to add the [(ngModules)]-attribute". If you think, this is the solution, please explain it why. Explain it, like you would do it to a child.

My Code in login.ts:

 import {Component} from '@angular/core';
 import {IonicPage, NavController, NavParams, MenuController} from 'ionic-angular';

@IonicPage()
@Component({
  selector: 'page-login',
  templateUrl: 'login.html',
})
export class LoginPage {
  password: string;

  constructor(public navCtrl: NavController, public navParams: NavParams, public menu: MenuController) {
    this.menu.enable(false, "");
  }

  login() {
    alert(this.password);
  }

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

The Code in login.html

<ion-content padding id="login-dialog">
  <ion-list inset>

    <ion-item no-padding>
      <ion-label color="primary">
        <ion-icon name="person"></ion-icon>
      </ion-label>
      <ion-input type="text" placeholder="Username"></ion-input>
    </ion-item>

    <ion-item no-padding>
      <ion-label color="primary">
        <ion-icon name="lock"></ion-icon>
      </ion-label>
      <ion-input type="password" placeholder="Password"></ion-input>
    </ion-item>
    <button ion-button full color="primary" (click)="login()">Login</button>

  </ion-list>

</ion-content>

1条回答
该账号已被封号
2楼-- · 2019-07-18 03:55

The above code will not work because you are not binding your input element to any property in the login component. You have to use angular data binding for that.

https://angular.io/docs/ts/latest/guide/template-syntax.html

Please change your code to the below.

<ion-item no-padding>
      <ion-label color="primary">
        <ion-icon name="lock"></ion-icon>
      </ion-label>
      <ion-input [(ngModel)]="password" type="password" placeholder="Password"></ion-input>
    </ion-item>

So whatever you type in the input will update the model (the property passsword you defined in your component). It will then alert the passsword.

查看更多
登录 后发表回答