简体   繁体   English

选中复选框时如何突出显示表格行? 角 7

[英]How do I highlight a table row when checkbox is selected? Angular 7

So let's skip the the table headers to my table body.所以让我们跳过表格标题到我的表格正文。 I have a populated table:我有一个填充表:

HTML: HTML:

<tbody>
   <tr *ngFor="let e of emails; let i = index">
   <td <input type="checkbox" id="email-checkbox" (change)="addToSelectedList($event, e)"></input></td>
   <td id="subject-{{i}}">{{e.sender}}</td>
   <td id="subject-{{i}}">{{e.subject}}</td>
   <td id="subject-{{i}}">{{e.date}}</td>
</tbody>

I want the table whole row to display a CSS class when the user checks the checkbox.当用户选中复选框时,我希望表格整行显示一个 CSS 类。 And then the color should go back to normal when the user deselects.然后当用户取消选择时颜色应该恢复正常。 Just UI stuff to show the user that an email has been selected.只是用于向用户显示已选择电子邮件的 UI 内容。 I currently have an empty CSS and .ts file.我目前有一个空的 CSS 和 .ts 文件。

The way you have done it here is more involved because presumably you have some logic inside addToSelectedList event that will add/remove the email depending on the checked state.您在这里完成的方式更复杂,因为大概您在 addToSelectedList 事件中有一些逻辑,可以根据选中的状态添加/删除电子邮件。 The easiest way is to add a property on the email entity isSelected, and do this:最简单的方法是在电子邮件实体 isSelected 上添加一个属性,然后执行以下操作:

<input  ... [checked]="e.isSelected" >

On your tr add the ngclass binding as suggested by others as follows:在您的 tr 上添加其他人建议的 ngclass 绑定,如下所示:

<tr [ngClass]="{ 'selectedcssclass' : e.isSelected }"...

Other observation in your code there isn't a closing tr that should be wrapping around all the tds.您的代码中的其他观察结果没有一个结束 tr 应该环绕所有 tds。

Not an Angular expert, but you can achieve just that using a JS onchange event bound to your checkbox:不是 Angular 专家,但您可以使用绑定到复选框的 JS onchange事件来实现这一点:

 $(".box").on("change", function() { $(this).parents("tr").toggleClass("highlight"); });
 .highlight { background-color: #ffff00; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table> <tr> <td>Label 1</td> <td><input type="checkbox" class="box"/></td> </tr> <tr> <td>Label 2</td> <td><input type="checkbox" class="box"/></td> </tr> </table>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM