【问题标题】:Select and change a single table cell color per row with angular 6使用角度 6 选择并更改每行的单个表格单元格颜色
【发布时间】:2019-03-12 23:01:55
【问题描述】:

我正在尝试制作一个表格,我可以在其中选择一个单元格并更改其颜色。每行只能选择 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"; }

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

【问题讨论】:

    标签: css angular select background


    【解决方案1】:
     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交互了解不多,但希望你能找到解决办法

    【讨论】:

    • 所以,在 tr 标签中我应该输入(click)="changeBG(event.target)"?然后将您的代码复制到我的代码中?对不起,我有点笨。 x)
    • changeBG($event.target) 和往常一样的功能,但是代码中有一个警告,因为 angular 并不意味着直接 dom 操作。但是,如果您是出于网络目的而制作它,那么我认为这没问题,并且代码可以正常运行。
    • 好吧,我想我做到了。不完全像你,寿。但无论如何。 :)
    猜你喜欢
    • 2012-09-07
    • 2011-04-27
    • 1970-01-01
    • 2015-10-09
    • 2017-08-07
    • 1970-01-01
    • 2015-01-24
    • 2020-12-28
    • 2015-04-28
    相关资源
    最近更新 更多