Creating a nested tree structure within a dropdown menu using Angular Material

Looking for guidance on implementing a tree view within a dropdown menu. The dropdown values will be retrieved from a REST API call in JSON format, with the potential of having multiple levels of child elements.

I also need to add an auto-suggestion feature that filters both parent and child elements.

 VehicleList = [
      {
        parent: "audi",
        child: [{
          type: 'G-audiA',
          subchild: [{
              id: 1,
              name: 'type audi A1'
          }, {
              id: 2,
              name: 'type audi A2'
          }]
        }, {
          type: 'G-audiB',
          subchild: [{
              id: 1,
              name: 'type audi B1'
          }, {
              id: 2,
              name: 'type audi B2'
          }]
        }]
      }, {
        parent: "bmw",
        child: [{
          type: 'G-bmwA',
          subchild: [{
              id: 1,
              name: 'type bmw A1'
          }, {
              id: 2,
              name: 'type bmw A2'
          }]
        }, {
          type: 'G-bmwB',
          subchild: [{
              id: 1,
              name: 'type bmw B1'
          }, {
              id: 2,
              name: 'type bmw B2'
          }]
        }]
  }]

Any assistance would be greatly appreciated!

Answer №1

After exploring the first example provided in the Angular Material Tree documentation, I successfully created a dropdown with a nested tree structure like this:

https://i.sstatic.net/rGTmB.png

To display the tree effectively, I added a disabled/empty option which served as a label. The tree structure was borrowed from the examples without any modifications, allowing flexibility for adjusting the node structure based on personal requirements.

To showcase the selected items within the dropdown label, you can implement a method that returns the selected items as a string. Utilizing the SelectionModel object's selected property makes it possible to retrieve all selected nodes efficiently.

/** Checklist selection */
checklistSelection = new SelectionModel<TodoItemFlatNode>(
    true /* multiple */
);

To retrieve the selected items from the tree:

return this.checklistSelection.selected.map(s => s.item).join(",");

https://i.sstatic.net/rlXcZ.png

If you need assistance with filtering, refer to this resource. I hope this proves helpful!

Stackblitz

Edit: Selecting a child will automatically select its parent and include it in the SelectionModel even if not all children are selected. To alter this behavior, you can comment out the descendantsPartiallySelected function. This adjustment prevents parents from being added to the SelectionModel unless all children are selected.

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

configure dynamic content within the slider element

Currently, I am experimenting with two jQuery plugins (awkward/Coda Slider 3) to implement a sliding effect for DIV content. Everything seems to be working smoothly until I attempt to set dynamic content (using JavaScript) after creating the plugin object. ...

Creating Dynamic Height for Div Based on Another Element's Height Using ReactJS and CSS

I'm attempting to set a fixed height for a div in order to enable overflow scrolling. However, I am encountering issues as I am using JavaScript within a useEffect hook to accomplish this task. The problem is inconsistent as sometimes the height is se ...

Tips for distinguishing between the fireauth login callback for Login and signup

Currently, I am developing an angular application that integrates with Firestore. I have incorporated Auth::createUserWithEmailAndPassword() to register a user and Auth::signInWithEmailAndPassword() to log in the user. In both scenarios, the user success ...

Guide to simulate the store.pipe method in an Angular component during unit testing

Just starting out with Angular and I'm trying to write unit tests for a component that retrieves data from the store. I've mocked both the service files and the store itself, but when running the test, I keep encountering the following error. Eve ...

Guide to automatically closing the calendar once a date has been chosen using owl-date-time

Utilizing Angular Date Time Picker to invoke owl-date-time has been functioning flawlessly. However, one issue I have encountered is that the calendar does not automatically close after selecting a date. Instead, I am required to click outside of the cal ...

What are the implications of implementing Ajax without relying on jQuery?

At a stage where I require Ajax on my webpage, but only for a specific section - checking if a username is present in the database. As detailed here, Ajax can be implemented using just JavaScript. What are the advantages and disadvantages of opting for t ...

Unable to bring in personalized typescript package in node.js

After struggling for hours trying to figure it out on my own, I finally decided to seek help on stackoverflow. I have a custom typescript project/package that I want to use with zx. I packed it using npm pack and installed the tar.gz globally. However, whe ...

In PHP, you can use the `echo` statement to output an HTML input

Incorporating HTML into PHP using heredoc methodology can sometimes lead to challenges when trying to retrieve user input variables. Attempting to access the input variable with $_GET["input"] may result in an error message indicating an undefined index: ...

Two-way binding in action: An illustrative example

After grasping the idea behind 2-way data binding, I am struggling to see its real-world application. It's difficult for me to envision a situation where both the client (UI) and the business owner have control over the data, especially after business ...

Do the values returned by window.screen.width and height represent CSS pixels or physical screen pixels?

After exploring the API named screen and visiting this documentation link, my initial anticipation was that I would receive information regarding actual screen size pixels. https://developer.mozilla.org/en-US/docs/Web/API/Screen/width https://i.sstatic.n ...

`I'm having issues trying to use ajax and load simultaneously``

Can anyone help me figure out why my AJAX call to sessions.php is not correctly loading and returning true or false each time a user accesses the page? var section = $("#header a"); section.on('click', function() { $.ajax({ type: "PO ...

Pass a method parameter in the subscribe function in Angular

I am looking to utilize the subscribe method within a function, in which I pass my variable (cities) as a parameter. export class MyComponent implements OnInit { cities:any; constructor(private myApiService: MyApiService) { myMethod(this.cities); ...

Prohibit using any as an argument in a function if a generic type is

I have attempted to implement this particular solution to prevent the calling of a generic function with the second type being equal to any. The following code snippet works fine as long as the first generic parameter is explicitly specified: declare fu ...

I'm encountering a 502 error while trying to use Supabase's signInWIthPassword feature

Despite all authentication functions working smoothly in my React, TypeScript, and Supabase setup, I'm facing an issue with signInWithPassword. In my context: I can successfully signIn, create a profile, and perform other operations like getUser() an ...

Error message: Unable to locate module when using a variable to import an image in React

I've encountered an issue with my React code that I can't seem to figure out. I am integrating the Accuweather API and trying to display the weather icon on my app. Initially, everything seemed to be working fine as I constructed the image path l ...

Navigating and Controlling the DOM in Angular 4

Can anyone help me figure out how to reach a DOM element in Angular 4? I'm really struggling with this concept and I've been trying to understand ElementRef, ViewChild, and other methods, but I just can't seem to grasp how to navigate throu ...

How can I create a dropdown menu that is dependent on another dropdown menu using Ajax in my Laravel application?

I have two dropdown fields that are dependent on each other - Class & Section. I am trying to Select * from sections where class_id=selected Class Id. Although I attempted to achieve this using java script, it doesn't seem to work for me. Here are ...

Using vuetify's v-autocomplete component with the options to select all and clear items

I am trying to incorporate a "Filter by values" feature in my application similar to Excel or spreadsheets. However, I am facing difficulty with implementing the 'Select all' and 'Clear' button in v-autocomplete. <v-col> < ...

Ways to reveal heavily nested components when the Angular change detector fails to detect them

A particular component called Grid has been implemented with the following template: <div *ngFor="let row of item.rows"> <div *ngFor="let col of row.cols"> <div *ngFor="let grid of col.items"> < ...

What is the best way to use jQuery to collapse input IDs?

Just a handful of inputs <input id=1> <input id=12> <input id=14> <input id=16> <input id=28> Seeking advice on how to combine these ids into a single string: '1,12,14,16,28'? ...