Issue
how to select all checkboxes in angular 6?
I'm trying to make a table with checkboxes but I cant set a checkbox that check true all checboxes in per page. I want to check all checkboxes but it isn't working correctly.
html
<table id="myTable">
<tbody >
</tbody>
<tbody >
<tr >
<th>
<input type=" checkbox" (change)="checkAll(this)">
</th>
<th>
id
</th>
<th>
fname
</th>
</tr>
</tbody>
<tbody *ngFor="let item of result" style="border:1px solid #D3D3D3">
<td>
<input type="checkbox" (change)="getCheckboxValues($event,item)" [checked]="check_true">
</td>
<td>
{{ item.id }}
</td>
<td>
{{ item.fname }}
</td>
</tbody>
</table>
component.ts
getCheckboxValues(ev, data) {
let obj = {
"order": data
}
let selected_rows = [];
if (ev.target.checked) {
// Pushing the object into array
this.newArray.push(obj);
} else {
let el = this.newArray.find(itm => itm.order === data);
if (el)
this.newArray.splice(this.newArray.indexOf(el), 1);
if (this.newArray.length == 0) {
this.newArray = [];
}
}
if (this.newArray.lenght > 0) {
for (let i in this.newArray) {
selected_rows.push(this.newArray[i].order.bulkid);
this.selected_rows = selected_rows;
}
}
}
checkAll(ele) {
var checkboxes = document.getElementsByTagName('input');
if (ele.checked) {
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].type == 'checkbox') {
checkboxes[i].checked = true;
}
}
} else {
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].type == 'checkbox') {
checkboxes[i].checked = false;
}
}
}
console.log(ele)
}
I'm trying to make a table with checkboxes but I cant set a checkbox that check true all checboxes in per page. I want to check all checkboxes but it isn't working correctly.
Solution
Prepared a small demo to show how this can be done using ngModel
directive. Link: https://stackblitz.com/edit/angular-lxjrdh
It uses Array.every
to check if all are checked or not. If checked, it resets all otherwise checks all.
Answered By - Saksham
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.