简体   繁体   中英

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:

<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. 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. I currently have an empty CSS and .ts file.

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. The easiest way is to add a property on the email entity isSelected, and do this:

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

On your tr add the ngclass binding as suggested by others as follows:

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

Other observation in your code there isn't a closing tr that should be wrapping around all the tds.

Not an Angular expert, but you can achieve just that using a JS onchange event bound to your checkbox:

 $(".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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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