Ionic3在ts中获取html中值的方法

2023-04-27,,

我觉得有两种方法,都是Angular中的语法,一种是把值当做参数传递,另一种是使用ngModel实现双向绑定

还有一种很少用到的,Js的原生方法:document.getElementById('chartContainer');

参数传递法

例子:获取input框内容

这里有个独特的地方,直接在input处使用 #定义参数的name值,注意在ts中参数的类型

在html页面中
  <ion-input type="text" placeholder="请输入账号" #username></ion-input>
  <ion-input type="password" placeholder="请输入密码" #password></ion-input>
  <button (click)="login(username, password)">登录</button>

在ts文件中

  login(username: HTMLInputElement, password: HTMLInputElement) {
    console.log(username.value)
    console.log(password.value)
  }

双向绑定法

这种方法比较通用,但是需要在ts中定义对应的变量

例子1:获取input框内容

在html页面中

  <ion-input type="text" placeholder="请输入账号" [(ngModel)]="username"></ion-input>
  <ion-input type="password" placeholder="请输入密码" [(ngModel)]="password"></ion-input>
  <button (click)="login()">登录</button>

在ts文件中

  username: string;
  password: string;
  login() {
    console.log(this.username);
    console.log(this.password);
  }

例子2:获取单选按钮的值

在html页面中
  <ion-toggle [(ngModel)]="rememberName"></ion-toggle>

在ts文件中
  rememberName: any;
  login() {
    console.log(this.rememberName);
  }

原创文章,欢迎转载,转载请注明出处

Ionic3在ts中获取html中值的方法的相关教程结束。

《Ionic3在ts中获取html中值的方法.doc》

下载本文的Word格式文档,以方便收藏与打印。