TransWikia.com

Array of Objects in Angular Material Tree

Stack Overflow Asked by carboneum on November 10, 2021

I want to display a tree of object.names as expandable nodes, when the user clicks on an object.name all propertys of this object, except the name, should be displayed as leaf nodes. I have followed this tutorial https://material.angular.io/components/tree/overview to create an flat tree.

You see they use this structure for the datasource:

...
{
    name: 'Fruit',
    children: [
          {name: 'Apple'},
          {name: 'Banana'},
          {name: 'Fruit loops'},
    ]
},
...

I have the following structure, which I receive from my backend:

...
{
    id: 1,
    name: "ServerConnection1",
    server: "Server1",
    enabled: true
},
...

I have managed to transfer my structure to be similar as the examples. You can see it in this stackblitz example:

https://stackblitz.com/edit/angular-q5f5nu

That enables me to show the properties as leaf nodes. Unfortunately I use string interploation to achive this because I didn’t found a way to receive the data in the template as keyValuePairs. My goal is to create an button next to the expandable node which enables the user to pass the object to a form. The form should display all the properties. It is hard to achive this when the Object keys are all named as "name". Is it possible to achive something like this with mat-tree?

EDIT: What I want to achive is to pass an Object of Arrays to the MatTreeFlatDataSource dataSource, that has an similar structure as my the Object which I receive from my backend.

I have the current structure MatTreeFlatDataSource dataSource:

current result in dataSource

which leads to this result in the template:

current result in template

The template result looks good, that was kind of a sucsess, but you see the Object keys are all named as "name". You can see that the mat-tree defines an variable in the template *matTreeNodeDef="let node". This is the Object which I want to pass to a form. At the moment it has the structure like you see in the pictures. I want to have something like this:

desired result

One Answer

To create a form for each extendable node, there should be only one leaf for a node, which is a form group. In that leaf you'll have as many inputs as you'd like. best if you'll add them hard coded.

If you'll use ReactiveFormsModule, than the leaf will be a form group, and the tree will be a form array.

When you create the data structure for the tree, also create the form structure. Create the FormArray in the same loop.

Check out the following example:

https://stackblitz.com/edit/angular-q5f5nu-a8bkvc?file=src%2Fapp%2Ftree-flat-overview-example.html

Answered by noam steiner on November 10, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP