Reputation: 4888
I'm using Tree with checkboxes, and I want to add a button to check all checkboxes, I tried different methods but no good, the best thing i was able to achieve is this:
selectAllFiscal() {
this.rootItems.forEach(node => {
this.todoItemSelectionToggle(node);
});
}
rootItems is an array of root nodes.
I can see that nodes are selected when I iterate checklistSelection.selected
, but the checkboxes are not selected in the browser, can anybody point the problem, thanks.
Upvotes: 4
Views: 13789
Reputation: 11081
Try the following for your method
checkAll(){
for (let i = 0; i < this.treeControl.dataNodes.length; i++) {
if(!this.checklistSelection.isSelected(this.treeControl.dataNodes[i]))
this.checklistSelection.toggle(this.treeControl.dataNodes[i]);
this.treeControl.expand(this.treeControl.dataNodes[i])
}
}
Stackblitz
https://stackblitz.com/edit/angular-hpsj5x?embed=1&file=app/tree-checklist-example.html
Upvotes: 7
Reputation: 134
The first answer has a bug in it, if you press select all and you already had selected a checkbox from the tree it s doing only toggle, not select/deselect-all. This is my solution:
In Html use something simillar to this:
<mat-checkbox [checked]="isAllSelected" (change)="selectAll()">Select all</mat-checkbox>
And in your component:
selectAll(): void {
this.select = !this.select;
this.treeControl.dataNodes.forEach((r, index) => {
this.treeControl.expand(this.treeControl.dataNodes[index]);
this.select
? this.checklistSelection.select(this.treeControl.dataNodes[index])
: this.checklistSelection.deselect(this.treeControl.dataNodes[index]);
});
this.isAllSelected = true;
}
Upvotes: 0