How to mark check box as a checked in angular 4

user3364549 picture user3364549 · Apr 18, 2018 · Viewed 21.2k times · Source

I am very new in angular 2. i need to mark check box on a button click. i have some checkbox in a loop like

 <tr *ngFor="let roleObj of roleNameList">
      <td>
         <input type="checkbox"   id ={{roleObj.roleID}} />
     </td>
     <td>{{roleObj.roleName}}</td>
  </tr>

i have one array of selected role, only i need to mark those check boxes on a edit button click . so what i did like same in javascript

 document.getElementById("role").checked

but in angular 4 there is no property like that.

i searched and found there is one property binding for

[checked] ="somevariable"

but the problem is same property [checked] ="somevariable" will add on all checkboxes. the result is when i assigned the somevariable as true. it will mark all the checkboxes.

other solution I have in jquery like

$(document.getElementById(role)).prop('checked', true);

but might be it can create problem, i am not sure please correct me.

please help me. any clue or logic will same my days.

Answer

bugs picture bugs · Apr 18, 2018

You can modify your object to also include a boolean checked property (i.e. roleObj.checked = false) and dynamically update the relevant ones when you need to.

Then you markup simply becomes

<input type="checkbox" [checked]="roleObj.checked" id ={{roleObj.roleID}} />