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

Vig*_* SP 5 typescript angular

我的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>
Run Code Online (Sandbox Code Playgroud)

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")
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我这样做是因为我不想获取具有其ID的输入元素,并查看它是否已检查。

这里的任何帮助/方向将不胜感激。

dev*_*ato 5

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>
Run Code Online (Sandbox Code Playgroud)

您需要检查event.target.checked以解决此问题。这是您可以实现的方式:

TS

onSelect(event) {
     if ( event.target.checked ) {
        // Your logic here
    }
}
Run Code Online (Sandbox Code Playgroud)
  1. 您应该使用 (change) 而不是 (click) 因为这是更好的做法
  2. 停止思考 JS。您现在正在使用 Typescript 和 Angular。这些框架存在是因为 vanilla JS 很烂所以当你使用这个很棒的库/框架时不需要继续编写 vanilla js