The "initialized" event in angular2-tree-component fires prior to the data being loaded

Utilizing the angular2-tree-component, my goal is to display an already expanded tree. According to Angular docs, the initialized event should be used for expanding the tree after the data has been received:

This event triggers after the tree model has been created. It is useful for performing actions immediately on initialization, such as expanding or activating specific nodes. The tree model can be accessed using a reference, as explained in the API section.

However, despite following the instructions, the tree does not expand after being rendered:

https://i.stack.imgur.com/JX5ZO.png

The data is loaded within the ngOnInit() method:

ngOnInit() {
    this.getApiFunction(request, item)
        .subscribe(x => {    
            console.log('before adjusting data');            
            this.adjustDataToTree(x);          
            console.log('after adjusting data');               
        });
}


adjustDataToTree(reports:any[]){        
    //cycle to process data for treeView
    for(...){...}
    this.Items.length = 0;
    this.Items = data from above cycle;        
}

Code snippet handling the initialized event:

onTreeLoad(){
    //alert('on Tree Load');
    this.tree.treeModel.expandAll();
    console.log('this.tree.treeModel.expandAll() is called!:)');       
}

This is how my tree is structured:

<tree-root (initialized)="onTreeLoad()" [nodes]="Items"  
    [options]="customTemplateStringOptions" #tree>        
    <ng-template class="expand-tree" #treeNodeTemplate let-node>
        <span (click)="currToggleExpanded(node)" *ngIf="node?.data?.expanded === true" 
            title="{{node.data.subTitle}}">{{ node.data.name }} {{ childrenCount(node) }} 
        </span>
        <span (click)="currToggleExpanded(node)" ngIf="!node?.data?.expanded === true" 
             title="{{node.data.subTitle}}">{{ node.data.name }} {{ childrenCount(node) }}
        </span>
    </ng-template>
</tree-root>

The initialized event is triggered before the data is actually loaded, evident from the order of logs:

https://i.stack.imgur.com/3sIIX.png

What am I missing or why is the initialized event firing before the data is loaded into the treeview?

Answer №1

Consider implementing an ngIf statement in your tree component to prevent rendering until the data is fully loaded

<tree-root *ngIf="Items" (initialized)="onTreeLoad($event)" [nodes]="Items"  
...>
    ...
</tree-root>

Additionally, make sure to pass the tree object through the initialized method onTreeLoad($event) and utilize that passed value. This step may not always be necessary if this.tree already references the same object.

onTreeLoad(tree): void {
    tree.treeModel.expandAll();
}

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

Creating a custom pipe that converts seconds to hours and minutes retrieved from an API can be achieved by implementing a transformation function

Can someone please provide guidance on creating a custom pipe in Angular 8 that converts seconds to hours and minutes? Thank you. <div class="col-2" *ngFor="let movie of moviesList"> <div class="movie"> {{ movie.attributes.title }} ...

Initialization of an empty array in Typescript

My promises array is structured as follows: export type PromisesArray = [ Promise<IApplicant> | null, Promise<ICampaign | ICampaignLight> | null, Promise<IApplication[]> | null, Promise<IComment[]> | null, Promise<{ st ...

Failed to send JSON data to WebMethod

I am encountering difficulties while attempting to send JSON to a WebMethod. I have provided the method I am using below. If there is a more efficient approach, please advise me. My goal is to store the JSON object in a database. JavaScript function TEST ...

What could be the reason behind my Ionic app receiving a 401 error from an API call while Postman is not encountering the

Following the instructions from a tutorial on Smart of the Home, I implemented the code below in a provider for my Ionic 2 App. return new Promise(resolve => { // Using Angular HTTP provider to make a request and process the response let headers = ...

Redux does not have the capability to insert an object into an array

I'm currently learning about redux and I've encountered an issue trying to add multiple objects into the initialState array. I attempted using the push() method, but it isn't working as expected. The submitter value is being passed to my act ...

Receiving and transmitting messages repeatedly in Discord.JS

Currently, I am developing a simple bot. Interestingly, the bot seems to be responding multiple times to a single command. Here is the code snippet: const Discord = require('discord.js'); var bot = new Discord.Client(); const PREFIX = "+"; var ...

Vue.js - The dissonance between data model and displayed output

Below is a simplified example of my issue: <html> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.1/jquery.min.js"></script> <script src="https://unpkg.com/vue/dist/vue.js"></script> ...

Creating a basic image carousel with JavaScript, CSS, and HTML

After running the code, I encountered an issue where the first image displays but then after one second, only a white blank screen appears with no further action. It seems like there may be an error in the JavaScript code. Below is the code that was attemp ...

Encountering issues when integrating an Angular library project into the main project

Currently, I am facing an issue with a library project (let's call it X) that contains 2 projects within it (X-core, X-core-members). My goal is to utilize this library in another angular project called ABC. I have made the necessary links in the tsco ...

What is the best way to arrange an array or display it accurately?

Guys, here's a challenge for you: extract the values from this JSON data: [[name, brand, oem, category], [name, brand, oem, category], [name, brand, oem, category], [name, brand, oem, category]] Check out my JavaScript code: $(function(){ $('i ...

`ng-apexcharts` causing unit test failures

I've been working on integrating apexcharts and ng-apexcharts into my home component. While I was able to get it up and running smoothly, it seems to be causing issues with my unit tests. Despite researching possible solutions, I haven't been abl ...

Error on Network: 400 BAD REQUEST in Ionic framework

I recently implemented push notifications successfully, but I am facing a network error with a 400 bad request when trying to access a specific API endpoint. The error message states: "NetworkError: 400 BAD REQUEST - https://apps.ionic.io/api/v1/app/77c3 ...

Utilizing the closest method to retrieve the form element

As I review code written by another developer, I came across a surprising method used to retrieve a form object. HTML for Login Form <form id="frm_login" action=""> <input type="text" name="username" id="username"> <input type="passwor ...

The withRouter function in React Router does not automatically inject the router

Desiring to implement withRouter on my primary React component named 'App'. You can view the documentation here. This is how I utilize it: import React from "react"; import { render } from "react-dom"; import {Router, Link, hashHistory, Rout ...

Angular list with a repeating group of radio buttons

I have a set of 'options', which consists of the following: {Id: 1, Label: "option 1"}, {Id: 2, Label: "option 2"} Additionally, I have a list of 'products' structured as follows: {Id: 1, Name: "Name 1", Recommend: options[0]}, {Id: ...

loop not functioning properly with file type input

Having trouble uploading an image and copying it into a folder named images within a loop. Can you assist with solving this issue? Here's my code: $sql="SELECT * FROM product"; $q=$conn->query($sql); while($r=$q->fetch(PDO::FETCH_ASSOC)) { $cod ...

Steps for calling a function in index.js using Node.js

I am just starting to learn about NodeJS and I have a question that might seem basic to some, but I would really appreciate some assistance here. Here is the content of my index.js file:- 'use-strict'; const { myauth } = require('./src/au ...

Replace the image source with a list of images

I am looking to create a dynamic image list using either an array or an HTML list. When I hover over an image, it should change one by one with a fade or slide effect, and revert back to the default images when I hover out. Question 1: What type of list s ...

The act of exporting components from the main index file allows for

I have assigned a components folder where I created various components that I want to export to the index.js file and then export all of them from there. This is an example from one of the components files: export default ToggleSwitch; Now, in the inde ...

Vue js version 2.5.16 will automatically detect an available port

Every time I run the npm run dev command in Vue.js, a new port is automatically selected for the development build. It seems to ignore the port specified in the config/index.js file. port: 8080, // can be overwritten by process.env.PORT, if port is in u ...