EmaRad
EmaRad

Reputation: 11

Angular 2 dynamic expendable nested lists

I have this dynamic list created with ngFor. When I click on item I want to expand it with new dynamic list, but only for that item. In my following code it expends for every item in the first list. I understand why that is happening, but I don't have ideas how to solve it.

Here is my code

 <ul *ngFor="let p of portList">
    <li  (click)="setONUList(p.name)" id="{{ p.name }}"><img src="app/resources/{{ p['oper-status'] }}.png" class="myimage"/>{{ p.name}}</li>
        <ol *ngFor="let onu of portONUList">
        <li><img src="app/resources/{{ onu['oper-status'] }}.png" class="myimage" />{{ onu.name}}</li>
      </ol>

  </ul>

Any ideas how to solve this would be very helpful.

Upvotes: 1

Views: 3210

Answers (2)

AVJT82
AVJT82

Reputation: 73357

From what I understand, the subarray is the same which is shown for all your items, so there is no relation between the nested array and the outer array.

My suggestion would actually be to add a new property in your array, e.g expanded... so e.g your outer array would look like:

portList = [{id:1,name:'one',expanded:false},{id:2,name:"two",expanded:false}];

And then your HTML:

<ul *ngFor="let p of portList">
  <li (click)="expand(p)">{{ p.name}}</li>
  <div *ngIf="p.expanded">
    <ol *ngFor="let onu of portONUList">
      <li>{{ onu.name}}</li>
    </ol>
  </div>
</ul>

And on click, toggle the expanded property:

expand(p: any) {
   p.expanded = !p.expanded;
}

Of course if you want to have a "quick" solution you could rely on HTML5 with no need of the new property:

<details *ngFor="let p of portList">
  <summary>{{p.name}}</summary>
    <ul *ngFor="let onu of portONUList">
      <li>{{ onu.name}}</li>
    </ul>
</details>

Here's a plunker with both options.

Upvotes: 3

Venkateswaran R
Venkateswaran R

Reputation: 478

There should be a relation between parent and childlist and the list should be in json format. Refer below code

<ul>
        <li ng-repeat="item in parent" ng-click="showChilds(item)">
            <span>{{item.name}}</span>
            <ul>
                <li ng-repeat="subItem in item.subItems" ng-show="item.active">
                    <span>{{subItem.name}}</span>
                </li>
            </ul>
        </li>
    </ul>

Sample JSON FORMAT

let parent= [
        {
            name: "Item1",
            subItems: [
                {name: "SubItem1"},
                {name: "SubItem2"}
            ]
        },
        {
            name: "Item2",
            subItems: [
                {name: "SubItem3"},
                {name: "SubItem4"},
                {name: "SubItem5"}
            ]
        },
        {
            name: "Item3",
            subItems: [
                {name: "SubItem6"}
            ]
        }
    ];

Upvotes: 0

Related Questions