首页 > 解决方案 > 使用角度 6 选择并更改每行的单个表格单元格颜色

问题描述

我正在尝试制作一个表格,我可以在其中选择一个单元格并更改其颜色。每行只能选择 1 个单元格。选中后,其颜色应为红色。单击另一个时,其颜色应变回以前的颜色。我已经尝试了几天,但没有成功。只改变了整行或整列的颜色,而不是单个单元格的颜色。可以做到吗?这是我的模板代码:

 <table id="table2"  class="table table-bordered text-center">
    <thead class="thead-light">
      <th>Criteria</th>
    </thead>
    <tbody>
    <tr *ngFor="let criter of rows;">          
      <td>{{ criter.criteria1 }}</td>
      <td>{{ criter.criteria2 }}</td>
      <td>{{ criter.criteria3 }}</td>
      <td>{{ criter.criteria4 }}</td>
    </tr>    
  <tbody>
  </table>

至于CSS,它只需要这个类(我认为):

.on { background-color: "red"; }

这就是提款机。如果您需要更多信息,请告诉我。任何帮助,将不胜感激。

标签: cssangularselectbackground

解决方案


 changeBG(val) { // on tr element
    // val is event.target
    let table = document.querySelector('#table2');
    let selectedCells = table.getElementsByClassName('on');
    if (val.tagName !== 'TD') {
        return;
      }
    if (selectedCells.length) {
      selectedCells[0].className = '';
    }
    val.className = 'on';
  }

我对 angular dom 交互了解不多,但希望你能找到解决方法


推荐阅读