ionic在ts中获取html中的值

版权声明:本文为作者原创,转载请注明出处。 https://blog.csdn.net/vop444/article/details/81590342

传值方法:

目前暂时掌握的有两种方法来传值,一种是利用 [(ngModel)] 双向绑定,另一种和平常html中一样把值当作参数传递。

{[ngModel]}双向绑定法

html中 利用[(ngModel)]获取ts传过来的值,同时对值修改后可再传回ts,也就是说,ts和html中其中一个变,另一个就跟着改变。

html代码

  <ion-card>
    <ion-list>
      <ion-item>
        <ion-label>昵称</ion-label>
        <ion-input type="text" [(ngModel)]="user.nickName"/>
      </ion-item>
    </ion-list>
  </ion-card>

ts代码

定义数组

//定义user数组接收后台传来的数据同时若使用双向绑定还可接受前台传来的数据给到后台
  public user = {
    id: '',
    image: '',
    name: '',
    wechat: '',
    nickName: '',
    sex: '',
    totalMcoin:''
  }
 //将页面的值赋值给实体
    let name = this.user.name;
    let sex = this.user.sex;
    let nickName = this.user.nickName;
    let id = "HzftzQnYHkMCpa7ijrU89Z"
    let totalMcoin = this.user.totalMcoin;

获取单选按钮的值

html代码

 <ion-toggle [(ngModel)]="rememberName"></ion-toggle>

ts代码

rememberName: any;
  login() {
    console.log(this.rememberName);
  }

参数传递方法

此处可直接在需要传值的控件上使用 #定义参数的值,然后通过时间传值至ts即可

如下代码,此时要传的参数为#name和#userId,只需要在对应的控件中写上#参数即可,然后当触发ChangeOk事件时传值。

html代码

 <ion-list>
    <ion-item class="Single-data" *ngFor="let item of items">
      <ion-label>
        <img class="imgEmpty" src="assets/imgs/touxiang.jpg" />
        <label #uName class="reason">{{ item }}</label>
        <span #uId class="idSpan">{{item.id}}</span>
      </ion-label>
      <ion-checkbox (ionChange)="ChangeOk(name,userId)"></ion-checkbox>
    </ion-item>
  </ion-list>

然后在ts接收即可,注意,此时传来的是label和span中所有的值,所以需要在uId和uName后.innerText即可。

ts代码

 public changeOk(uName:any,uId:any) {
    let data= {
        id:uId.innerText,
        name:uName.innerText
    }
    this.pick.push(data);
    // JSON转换成string保存在localStorage
    this.strPick=JSON.stringify(this.pick)
    localStorage.setItem('pick',this.strPick)
  }

需要注意的是并不是所有的值都是.innerText,如下例子

html代码

<ion-list>
    <ion-item>
      <ion-input #jeason type="text" placeholder="加分原因"></ion-input>
    </ion-item>
  </ion-list>

  <ion-item>
    <ion-label>选择分值</ion-label>
    <ion-datetime #integral displayFormat="DD" pickerFormat="DD" cancelText="取消" doneText="确认"></ion-datetime>
  </ion-item>

  <button ion-button class="BtnPlusBonus" color="light" round (tap)="BtnPlusBonus(userId,jeason,integral)">加 分</button>

ts代码

  // 点击加分按钮
  BtnPlusBonus(userId: any, reason: any, integral: any) {
    reason = reason._value;
    integral = integral._text;
    }

感谢阅读,本文章部分参考:https://www.cnblogs.com/acm-bingzi/p/ionicParam.html

猜你喜欢

转载自blog.csdn.net/vop444/article/details/81590342