选中复选框时如何突出显示 table 行? Angular 7
How do I highlight a table row when checkbox is selected? Angular 7
所以让我们跳过 table headers 到我的 table body。我有一个填充 table:
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>
我希望 table 整行在用户选中复选框时显示 CSS class。然后当用户取消选择时颜色应该恢复正常。仅 UI 向用户显示已选择电子邮件的内容。我目前有一个空的 CSS 和 .ts 文件。
不是 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>
您在此处完成的方式更加复杂,因为您可能在 addToSelectedList 事件中有一些逻辑将 add/remove 根据选中状态发送电子邮件。最简单的方法是在电子邮件实体 isSelected 上添加一个 属性,然后执行此操作:
<input ... [checked]="e.isSelected" >
在您的 tr 上添加其他人建议的 ngclass 绑定,如下所示:
<tr [ngClass]="{ 'selectedcssclass' : e.isSelected }"...
您的代码中的其他观察结果没有应该包含所有 tds 的结束 tr。
所以让我们跳过 table headers 到我的 table body。我有一个填充 table:
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>
我希望 table 整行在用户选中复选框时显示 CSS class。然后当用户取消选择时颜色应该恢复正常。仅 UI 向用户显示已选择电子邮件的内容。我目前有一个空的 CSS 和 .ts 文件。
不是 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>
您在此处完成的方式更加复杂,因为您可能在 addToSelectedList 事件中有一些逻辑将 add/remove 根据选中状态发送电子邮件。最简单的方法是在电子邮件实体 isSelected 上添加一个 属性,然后执行此操作:
<input ... [checked]="e.isSelected" >
在您的 tr 上添加其他人建议的 ngclass 绑定,如下所示:
<tr [ngClass]="{ 'selectedcssclass' : e.isSelected }"...
您的代码中的其他观察结果没有应该包含所有 tds 的结束 tr。