Populate a Treeview in Angular2/PrimeNG with dynamic item insertion

Received data from a server has varying numbers of slashes in the path structure, like:

abc/abca/abcsd/absc.dat

I am attempting to display this data in a treeview using PrimeNG. I have made some progress:

for (var i = 0; i < this.test.length; i++) {
                let regex = /([^\/]+)\/?/g;
                let result: RegExpExecArray;

                while ((result = regex.exec(this.test[i])) !== null) {
                    console.log(result[1]);
                    if (result[1].search(".dat")>0) {
                        let item = {
                            "label": result[1],
                            "data": "Documents Folder",
                            "icon": "fa-file-text-o"
                        }
                        this.tree.push(item)
                    }
                    else {
                        let item = {
                            "label": result[1],
                            "data": "Documents Folder",
                            "expandedIcon": "fa-folder-open",
                            "collapsedIcon": "fa-folder",
                            "children": [{
                            }]
                        }
                        this.tree.push(item)
                    }
                }
            }

"test" contains the described data. Regular expressions help extract strings between slashes. However, the current code does not accurately represent the folder structure in the tree view.

To achieve a dynamic solution for displaying folders, instead of hardcoding based on slash count, I need something like this:

for 3 slashes:
   first item: this.items.push(item)
   sec. item : this.items[0].children.push(item)
   third. item: this.items[0].children[0].children.push(item)

for x slashes:
   ???

Looking for suggestions on how to dynamically organize and display the folder structure in the tree view.

Answer №1

To effectively navigate through a hierarchical structure like a tree, you must develop a recursive function that can call itself to handle child items. Below is a sample code snippet to illustrate the concept.

    for (let role of roles) {
        if (role.parentID) continue;

        const roleNode = this.createTreeNodesFromEntities(role, (x: Role) => x.roles);

        this.roleNodes.push(roleNode);
    }


private createTreeNodesFromEntities<T extends { name: string }>(entity: T, getChildren: (x: T) => T[]): TreeNode {
    let result: TreeNode = {
        label: entity.name,
        data: entity,
        expanded: true,
        children: []
    }

    getChildren(entity).forEach((childPermission, index) => {
        let cPermissionNode = this.createTreeNodesFromEntities(childPermission, getChildren);
        result.children.push(cPermissionNode);
    })

    return result;
}

If you need further guidance, you might find additional insights in this resource. I hope this explanation clarifies the process.

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

What is the method for retrieving a variable from a custom JavaScript file within an Angular component?

Currently, I'm actively involved in an Angular 5 project where I have included a custom JavaScript file called myfile.js inside the assets > js directory. In order to extract a particular value from myfile.js, I have created a component and now nee ...

FusionCharts encountered an error when attempting to display various charts using the same data source

I have a specific requirement to generate dynamic charts based on web service responses containing the chartType and formatted dataSet, but unfortunately, FusionCharts cannot fulfill this task effectively. In the example below, let's assume that the ...

Why do my messages from BehaviorSubject get duplicated every time a new message is received?

Currently, I am using BehaviorSubject to receive data and also utilizing websockets, although the websocket functionality is not relevant at this moment. The main issue I am facing is why I keep receiving duplicated messages from BehaviorSubject. When exa ...

Could we apply 'ngZone: 'noop' specifically to a function or component in Angular?

I am currently utilizing a third-party library to create PowerPoint presentations in Angular (Version 5). The third-party library makes numerous asynchronous calls and promises, causing zone.js to keep track of more than 50 loops running simultaneously. Th ...

Unable to access attributes of an object that has not been defined (referencing 'providers')

https://i.sstatic.net/9Ntvd.png When I try to import web3 version 1.2.11, I am using the following code in TypeScript: import Web3 from 'web3' const readonlyProvider = new Web3.providers.HttpProvider(providerURL) However, after compiling it, ...

Designing a filter system based on price ranges using checkboxes

import { useState } from 'react'; const Shop = ({capes}: Props)=>{ const[checkVal1, setCheckVal1]= useState(0); const[checkVal2, setCheckVal2]= useState(0); const[checkVal3, setCheckVal3]= useState(0); const[checkVal4, setCheckVa ...

Resetting Values in an Angular Reactive FormArray

Encountered an unusual bug while working with Angular reactive forms. I have set up a FormArray to manage a dynamic form where fields can be added or removed. My goal is to reset the form to its original state, including the values and number of form input ...

Next.js encountered an error when trying to locate the 'net' module while working with PostgreSQL

I'm facing a challenge in my Next.js project while attempting to retrieve all records from a table. The error message I'm encountering is "Module not found: Can't resolve 'net'" with an import trace pointing to multiple files withi ...

What is the best way to horizontally align an Angular mat-expansion-panel?

I have exhausted all my ideas trying to make this work. I made some changes to a different stackblitz as a test: https://stackblitz.com/edit/angular-acdxje-8bz7tq?file=app%2Ftable-basic-example.html,app%2Ftable-basic-example.css,styles.css,app%2Ftable-bas ...

A guide on using sinon to stub express middleware in a typescript project

I'm currently facing a challenge in writing an integration test for my express router using typescript, mocha, sinon, and chai-http. The router incorporates a custom middleware I created to validate JWT tokens present in the header. My goal is to moc ...

Retrieve the response type from a Prisma FindUnique query

Essentially, my goal is to determine the type of the result obtained from a FindUnique operation in Prisma. The current return type is any: import prisma from "@/libs/prismaDb"; import { Prisma } from "@prisma/client"; export default a ...

Utilizing Laravel 5.5 and Angular on a Subdomain

Currently, I am facing a challenge in setting up a small project that involves Laravel and Angular. My goal is to have the Laravel 5.5 backend running on domain.com while the Angular frontend is hosted on app.domain.com. I attempted to install Angular wi ...

Exploring the Scope of a Directive within an HTML Element's Event Handler

I devised a custom Directive for utilizing an element as a 'dropzone' with native HTML Drag & Drop functionality. Custom Directive Source Code import { Directive, ElementRef, OnInit, Output, EventEmitter, ViewChild } from '@angular/co ...

What is the best way to implement jQuery functions such as datepicker within an Angular Component file?

My Angular code snippet is below: index.html <script type="text/javascript" src="https://cdn.jsdelivr.net/jquery/latest/jquery.min.js"></script> <script type="text/javascript" src="https://cdn.jsdelivr.net/momentjs/latest/moment.min.js"&g ...

Tips on launching a bootstrap modal by clicking a button in an Angular project

I'm working with a Bootstrap Modal that includes a button to trigger it. Here is the code: <!-- Button trigger modal --> <button type="button" class="btn btn-primary" data-toggle="modal" data- ...

AngularJS: Integrating OAuth2 for RESTful API Development

I am currently working on incorporating OAuth2 authentication into my Angular 2 web project, which relies heavily on REST APIs. I have come across several ng-oauth2 packages that require a new login page for authentication, but I am in need of a restful au ...

In order to effectively manage the output of these loaders, it may be necessary to incorporate an extra loader. This can be achieved by using the

I'm currently working with react typescript and trying to implement a time zone picker using a select component. I attempted to utilize the npm package react-timezone-select, but encountered some console errors: index.js:1 ./node_modules/react-timezo ...

Zod Schema consolidates an array of objects into a single, comprehensive object

I have been working with a couple of schemas, where one contains an array of the other as a value. For example, const ActionSchema = {id: z.string(), name: z.string(), description: z.string()} const PersonSchema = { id: z.string(), actions: ActionSchema.a ...

how to make a "select all" checkbox with Angular 2

`I'm currently working on a feature that allows a checkbox to select all checkboxes within a specific div when checked. The div exclusively contains checkboxes. //TS FILE constructor() { } checkAll: ElementRef | undefined; selectAll(isChecked: ...

The observer error silently assumes an undefined type

Currently, I am attempting to implement the guidance provided in this Stack Overflow post on performing a File Upload using AngularJS 2 and ASP.net MVC Web API. The issue arises from the upload.service.ts file where an error is identified next to the prob ...