验证是否在Angular2中选中了输入复选框

前端之家收集整理的这篇文章主要介绍了验证是否在Angular2中选中了输入复选框前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我的 HTML中有一个表,每行中有一个单元格有一个输入复选框.

现在我正在尝试检查是否选中了复选框,以下是我尝试过的.

HTML:

<table class="table table-hover" id="just_a_table">
    <thead>
        <tr>
          <th scope="col">Select</th>
          <th scope="col">IP Addr</th>
        </tr>
    </thead>
    <tbody>
        <tr *ngFor="let data of instances">
          <td><input type="checkBox" (click)='onSelect()'></td>
          <td>{{data["IP"]}}</td>
        </tr>
    </tbody>
</table>

TS:

onSelect() {
    // We get the table data from the html and find if the checkBox is active.
    // The rows of the tables can be accessed by "rows" object and cells can be accessed using "cells" object.
    this.table_data = document.getElementById("just_a_table")

        for (var i=1,row; row = this.table_data.rows[i]){
          for (var j=0,cell; cell = row.cells[j]){
            if (<HTMLInputElement>cell[1].checked){
              console.log("It is checked")
            }
        }
    }
}

我正在这样做,因为我不想得到带有它ID的输入元素,看看是否检查过.

任何帮助/方向在这里将非常感激.

解决方法

HTML

<table class="table table-hover" id="just_a_table">
       <thead>
           <tr>
               <th scope="col">Select</th>
               <th scope="col">IP Addr</th>
           </tr>
        </thead>
        <tbody>
           <tr *ngFor="let data of instances">
               <td><input type="checkBox" (change)='onSelect($event)'></td>
               <td>{{data["IP"]}}</td>
           </tr>
        </tbody>
   </table>

您需要检查event.target.checked以解决此问题.这就是你如何实现这一目标:

TS

onSelect(event) {
     if ( event.target.checked ) {
        // Your logic here
    }
}

>你应该使用(改变)而不是(点击)因为它更好实践>停止思考JS.你现在正在使用Typescript和    角.存在这些框架是因为香草JS很糟糕,所以没有必要    当你使用这个真棒时,继续写香草js    库/框架

猜你在找的Angularjs相关文章