Having trouble selecting all checkboxes in the tree using angular2-tree when it first initializes

My goal is to have all checkboxes auto-checked when clicking the "feed data" button, along with loading the data tree. I've attempted using the following code snippet:

this.treeComp.treeModel.doForAll((node: TreeNode) => node.setIsSelected(true)); 

However, this approach does not seem to be working as intended. Below is the relevant section of my code:

click(tree: TreeModel) {
    // Code implementation here
}

selectAllNodes() {
    // Code implementation here
}

onTreeLoad(){
    console.log('tree');
}

// Other methods and event handlers follow...

You can view the full code on StackBlitz here.

Answer №1

To ensure all checkboxes are checked in the tree view, use the updatedata and initialized events.

app.component.html

<tree-root #tree *ngIf ="nodes" [nodes]="nodes" [options]="options" [focused]="true"
    (initialized)="onTreeLoad()"
    (updateData)="updateData()"
    (select)="onActivate($event)"
    (deselect)="onDeactivate($event)">
</tree-root>

The tree-root component will only be initialized if the nodes variable is present. Once initialized, use the selectAllNodes method within the initialized and updateData events to check all checkboxes.

app.component.ts

updateData() {
  this.selectAllNodes();
}

onTreeLoad(){
  this.selectAllNodes();
}

For a live example, refer to this slackblitz.

Answer №2

For your function to properly feed data, make sure to call this.selectAllNodes() within a setTimeout. Check out the modified stackblitz for reference.

setTimeout(()=>{
   this.selectAllNodes()
})

NOTE: I noticed in your code that you are trying various methods to select items. I have simplified it using a recursive function.

The selected items that have changed are stored in this.treeComp.treeModel.selectedLeafNodeIds, so

  getAllChecked()
  {
    const itemsChecked=this.getData(
              this.treeComp.treeModel.selectedLeafNodeIds,null)
    console.log(itemsChecked);
  }

  getData(nodesChanged,nodes) {
    nodes=nodes||this.treeComp.treeModel.nodes
    let data: any[] = []
      nodes.forEach((node: any) => {
        if (nodesChanged[node.id]) 
          data.push({id:node.id,name:node.name})
          if (node.children)
              data=[...data,...this.getData(nodesChanged,node.children)]
      }
      );
    return data
  }

Update: I have enhanced the function getData to include the node's "parent", although I find @Raghul selvam's code more appealing than mine.

getData(nodesChanged,nodes,prefix) {
    nodes=nodes||this.treeComp.treeModel.nodes
    let data: any[] = []
      nodes.forEach((node: any) => {
        if (nodesChanged[node.id])
          data.push(prefix?prefix+"."+node.name:node.name)
          if (node.children)
              data=[...data,...this.getData(nodesChanged,node.children,prefix?prefix+"."+node.name:node.name)]
      }
      );
    return data
  }

Simply call it like this

this.getData(this.treeComp.treeModel.selectedLeafNodeIds,null,"")

Answer №3

To implement this functionality, consider adding the following code snippet to your onTreeLoad function. It involves setting a boolean flag named 'treeLoaded' to keep track of the tree loading status.

onTreeLoad(tree){

   this.selectAllNodes();
    this.treeLoaded = true;
  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

AngularJS allows you to dynamically disable a button based on a value in an array

I have an array containing letters from A to Z and I want to create a list of buttons using them. $scope.alphabet = "abcdefghijklmnopqrstuvwxyz".split(""); I also have another array: $scope.uniqChar = ['a', ' ...

ThymeLeaf does not support the parsing of JavaScript code

I'm working on serving an Angular app with spring boot/thymeleaf. This is the structure of my class that sends html/css/javascript: @Controller public class ResourceProvider { @RequestMapping(method = RequestMethod.GET, value = "/") ...

Mixing Jest and Cypress in a TypeScript environment can lead to Assertion and JestMatchers issues

When utilizing [email protected] alongside Jest, we are encountering TypeScript errors related to Assertion and JestMatchers. What is the reason for these TypeScript errors when using Jest and [email protected] in the same project? ...

Guide to Incorporating a Marker into an SVG Blinking Rectangular or Circular Border Image on Google Maps

I have a link that points to a specific location on Google Maps using latitude and longitude: http://www.google.com/intl/en_us/mapfiles/ms/micons/red-dot.png Now, I am looking to add a blinking border to this marker link. Is there a way to achieve this ...

Exploring the significance of a super in Object-Oriented Programming within JavaScript

During my studies of OOP in JS, I encountered the super() method which serves to call the constructor of the parent class. It made me ponder - why is it necessary to invoke the parent class constructor? What significance does it hold for us? ...

Establishing a secondary setTimeout function does not trigger the execution of JQUERY and AJAX

// Custom Cart Code for Database Quantity Update $('.input-text').on('keydown ' , function(){ var tr_parent = $(this).closest("tr"); setTimeout(function () { $(tr_parent).css('opacity', '0.3'); }, 4000); var i ...

Please identify the path of chromedriver for selenium-standalone

I've encountered an issue when trying to initialize the selenium-standalone server (https://www.npmjs.com/package/selenium-standalone). The error message I receive is as follows: 14:19:09 /usr/local/lib/node_modules/selenium-standalone/bin/selenium-s ...

JavaScript refuses to execute

I am facing an issue with a static page that I am using. The page consists of HTML, CSS, and JavaScript files. I came across this design on a website (http://codepen.io/eode9/pen/wyaDr) and decided to replicate it by merging the files into one HTML page. H ...

Can a string array be transformed into a union type of string literals?

Can we transform this code snippet into something like the following? const array = ['a', 'b', 'c']; // this will change dynamically, may sometimes be ['a', 'e', 'f'] const readonlyArray = arr ...

Unable to obtain the accurate response from a jQuery Ajax request

I'm trying to retrieve a JSON object with a list of picture filenames, but there seems to be an issue. When I use alert(getPicsInFolder("testfolder"));, it returns "error" instead of the expected data. function getPicsInFolder(folder) { return_data ...

Unexpected results can occur when using ngClass and CSS with all unset

Within my Angular 4 project, I am utilizing ngClass on an object that contains a CSS class applied with unset: all within it. Despite knowing that ngClass adds its properties, the expected result was for all values to be unset and the style elements from n ...

Having trouble importing components from the module generated by Angular CLI library

After creating a simple Angular library using CLI with the command ng g library <library-name>, I encountered an issue while trying to import a component from its module. In my app module, I added components.module to the imports array and attempted ...

Error message: While running in JEST, the airtable code encountered a TypeError stating that it cannot read the 'bind' property of an

Encountered an error while running my Jest tests where there was an issue with importing Airtable TypeError: Cannot read property 'bind' of undefined > 1 | import AirtableAPI from 'airtable' | ^ at Object.&l ...

Use JavaScript to gather various data forms and convert them into JSON format before transmitting them to PHP through AJAX

My understanding of JSON might be a bit off because I haven't come across many resources that discuss posting form data via JSON/AJAX to PHP. I often see jQuery being used in examples, but I have yet to delve into it as I've been advised to firs ...

What is the best way to incorporate background colors into menu items?

<div class="container"> <div class="row"> <div class="col-lg-3 col-md-3 col-sm-12 fl logo"> <a href="#"><img src="images/main-logo.png" alt="logo" /> </a> ...

Ending asynchronous tasks running concurrently

Currently, I am attempting to iterate through an array of objects using a foreach loop. For each object, I would like to invoke a function that makes a request to fetch a file and then unzips it with zlib, but this needs to be done one at a time due to the ...

Transforming a base64 encoded string into a byte array

I have implemented a form where users can upload images to the page using an <input id = "fileLoader" type = "file" />. With JavaScript, I convert these uploaded images to base64 and send them to the server. On the server side, I need to decode this ...

JavaScript: Responding to the fetch response based on certain conditions

I am currently working with a fetch() request that can either return a zip file (blob) or a JSON object in case of an error. The existing code successfully handles the zip file by sending it to the user's Downloads folder. However, when a JSON respons ...

What is the best way to develop interactive components using Google App Scripts for Google Sites?

I am currently working on building dynamic app script components that can be seamlessly integrated into my website, each with unique data for every instance of the script. I initially attempted using parameters but I'm uncertain if this is the most ef ...

Delete one item from a group of objects[]

In my TypeScript code, I have a declared object like this: public profileDataSource: { Value: string, Key: number }[]; This results in an object structure that looks similar to the following: 0: Object {Value: "<Select Profile>", Key: null} ...