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

Add opening and closing HTML tags to enclose an already existing HTML structure

Is there a way to dynamically wrap the p tag inside a div with the class .description-wrapper using JavaScript or jQuery? This is the current html structure: <div class="coursePrerequisites"> <p> Lorem ipsum.. </p> </ ...

javascript extract data from JSON

How can I extract values from the [object Object] in javascript? I have a JSON response from PHP that I am passing into JavaScript. I want to retrieve the GPSPoint_lat and GPSPoint_lon values. var jArray = ; var obj = JSON.parse(jArray); I am gett ...

What is the best approach to create a JavaScript search filter function spanning two pages?

Page1.html has a form with a drop-down menu containing options Color and Shape. There is also a submit button. Assuming Page2.html displays various shapes like Blue Square, Red Square, Blue Circle, Red Circle, is it feasible to create a JavaScript file th ...

What solutions are available to resolve the routing problem in React.js?

On my fourth day working with Node and React.js, I am creating a custom offline search function for Docusaurus 2. I've built a JSON index and implemented a search function using elasticlunr. My goal is to redirect to a separate results page, but I&apo ...

Encountering an issue while trying to initiate npm start command for a ReactJS application on an

While attempting to deploy my node and react app on AWS ec2, I encountered an issue. The node app is working fine, but the react app is giving an error when running npm run build. I also tried using npm start, but unfortunately, it resulted in the same er ...

Creating a type-safe method wrapper in TypeScript based on function names

Many Q&As discuss creating a function wrapper in TypeScript, but my question is how to do the same with named methods. I am interested in writing something similar to this JavaScript code: function wrap(API, fnName, fn) { const origFn = API.p ...

Preserve the iframe src value in the dropdown menu even after the page is refreshed

I am trying to figure out how to prevent the iframe src from changing when I refresh the page, unless the user manually changes it using the dropdown menu with JavaScript. Can someone help me with this? <div class="row"> <div class="span9"> ...

The background on my modal remains unchanged

I have integrated a modal using Iframe for user login/registration on my website. Here is the HTML code: <div class="modal" id="ays-popin-connexion" aria-hidden="true"> <div class="modal-body" aria-hidden="true"> <iframe src=" ...

Unable to retrieve data from file input using jQuery due to undefined property "get(0).files"

I am facing an issue with retrieving file data in jQuery AJAX call from a file input on an ASP.NET view page when clicking a button. HTML <table> <td style="text-align:left"> <input type="file" id="AttachmenteUploadFile" name="Attachme ...

How to troubleshoot the issue of "Error: (SystemJS) module is not defined" in Angular 2?

I am a beginner in the world of Angular2. It is known that in Angular2, there is a way to reference a file using a relative path by defining moduleId : module.id in the component meta data. However, I have tried doing it this way and keep encountering the ...

The compatibility issues between Karma and Jasmine testing configurations cause errors during the Ionic packaging process

I've recently added testing to my ionic app using karma + jasmine, along with a typescript pre-processor. Below are the dependencies I have, most of which were added specifically for testing: "devDependencies": { "@ionic/app-scripts": "1.0.0", ...

Angular.js reports that the custom HTTP response header is missing

Despite Chrome showing the correct POST response headers, my custom HTTP header X-Auth-Token is returning null in the callback function for the POST request. Angular.js seems to only be returning Cache-Control and Content-Type, with everything else showing ...

Is combining Passport.js Google authentication with JWT a logical choice?

I am currently working on integrating Google Login with Passport.js into my MERN stack application. However, I have created this middleware for JWT authentication: const jwt = require("jsonwebtoken"); const config = require("config"); module.exports = a ...

What is the cost associated with using the require() function in an Express.js application?

I have a web application built with Express.js that serves one of my domains. The structure of the app.js file is as follows: var express = require('express'); var app = express(); // and so on… To incorporate one of my custom functions in t ...

Navigate divs with varying z-index values

I want to change the z-index of 3 divs by toggling them using jQuery, but I'm not sure how to do it. What I want is to click a button that relates to a specific div and increase the z-index of that div so the content inside it is shown. Currently, all ...

Error encountered during Angular upload using Asp.net core: System.Text.DecoderFallbackException is thrown when bytes [FF] cannot be translated at the specified index

I am having trouble uploading a file using Angular 7 and Asp.net core 2.2 I have set up the Angular web service to append the file and include a property Name. However, when I call the WebService from Angular, I encounter an error in the Asp.net core l ...

What is the best way to represent a state with two possible fields in React using TypeScript?

There is a specific state item that can have its own value or reference another item using an ID. interface Item { itemName: string; itemValue: { valLiteral: number } | { idNumber: string }; } const indItem1: Item = { itemName: "first sample&quo ...

Generating HTML widgets dynamically with jQuery: A step-by-step guide

Looking for a way to display an interactive widget on your page while allowing users to generate multiple instances and interact with them simultaneously? Imagine having a widget like this: <div id="my_widget"> <script type="text/javascript" ...

Injecting universal data into ValidationErrors in Angular

Trying to bind a value into ValidationErrors. Having this method: isUniqueEmail(control: FormControl): ValidationErrors { if (control.value != null) { console.log(control.value) if(control.value == this.foundEmail){ console ...

What is the best way to anchor the components to a specific location on the screen in ASP.NET?

Currently I am working on creating a registration page in asp.net. I have been using panels to group the components such as labels, dropdown lists, and text boxes. However, when I run the page, I noticed that the positions of these components keep changing ...