0

I have an array of elements that look like this:

elements = [
{name: 'Root1', id: 1, parent_id: null},  
{name: 'Child1', id: 2, parent_id: 1}, 
{name: 'Child11', id: 3, parent_id: 2},
{name: 'Child211', id: 8, parent_id: 7}
{name: 'Child12', id: 4, parent_id: 2} 
{name: 'Root2', id: 5, parent_id: null}, 
{name: 'Child2', id: 6, parent_id: 4},
{name: 'Child21', id: 7, parent_id: 5},
]

I'd like to have a select box where only the children can be selected (indicated by the < symbol) and that looks like this:

Root1
  Child1
    Child11 <
    Child12 <
Root2
  Child2
    Child21
      Child211 <

I've tried using Ng-Select's Groupby, grouping by parent_id, but it didn't work very well.

Using the following code:

<ng-select
  [items]="elements"
  bindLabel="name"
  bindValue="parent_id"
  groupBy="parent_id"
  [(ngModel)]="selectValue"
  >
<ng-template ng-optgroup-tmp let-item="item">
  {{ item.name || item.parent_id }}
</ng-template>
</ng-select>

The groups ended up looking like this:

Root1
  Child1 <
Child1
  Child11 <
  Child12 <
Root2
  Child2 <
Child2
  Child21 <
Child21
  Child211 <
Root1 <
Root2 <

How do I solve this problem? Do I need a new structure?

EDIT: My elements list can grow or shrink at any time, so the suggested answer doesn't help me.

  • Does this answer your question https://stackoverflow.com/questions/1037732/nesting-optgroups-in-a-dropdownlist-select – Owen Kelvin Jan 21 '21 at 04:17
  • It doesn't, as I'm trying to dynamically generate my using Ng-Select. My list of Select elements can grow at any time. – Felipe Vieira Jan 21 '21 at 11:15

0 Answers0