4

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.

2 Answers 2

7

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

Sign up to request clarification or add additional context in comments.

2 Comments

this has a bug in it, if you already had selected a node, when you press checkAll is deselecting the already existing selection
See revision to stackblitz. You are correct, but you can leverage the isSelected() function of the SelectionModel. This in my opinion would be less verbose and a more readable syntax for your development team members versus using this.select in your solution.
0

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;
  }

2 Comments

You should use this.checklistSelection.isSelected() to check the current state of the checkbox, it is what the function is there for. See revision above to the original answer.
@Marshal you need to keep track of your flag for the toggle effect.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.