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


我覺得有兩種方法,都是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);
  }

 

原創文章,歡迎轉載,轉載請注明出處


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM