How to show and hide sublists in a recursive ng-template in Angular?

947 Views Asked by At

I looked up a lot of different answers here but most of them are not accurate. So, I wanted to ask what a good approach would look like to show and hide lists (ul) but only the list which was clicked on via onclick.

I have the following tempplate

        <ul *ngIf="children">
            <ng-container *ngTemplateOutlet="recursiveListTmpl; context:{ $implicit: children }"></ng-container>
        </ul>
          
          <ng-template #recursiveListTmpl let-children>
          <li *ngFor="let item of children; let i=index">
              {{item.name}}
              <ul *ngIf="item.children" class="sublists">
                  <ng-container *ngTemplateOutlet="recursiveListTmpl; context:{ $implicit: item.children }"></ng-container>
              </ul>
          </li>
          </ng-template>

Children is an array of objects containing a name and further children.

I tried to bind specific classes for each sublist and then get those element via document.getElementsByClassNamesbut it did not work correctly.

Do you have any currently correct approach to tackle my problem? How should I try to toggle those sublists? I really have no idea anymore... My Angular Version is 9.

1

There are 1 best solutions below

2
Usman Ali On

you can add hidden of type boolean in your list, by default it is false, when you want to show the sublist, change it to true

For example

          <li *ngFor="let item of children; let i=index">
              <div *ngIf="item.hidden">
                  {{item.name}}
                  <ul *ngIf="item.children" class="sublists">
                  <ng-container *ngTemplateOutlet="recursiveListTmpl; context:{ $implicit: item.children }"></ng-container>
                  </ul>
              </div>
              <button (click)="showHide(item)">Show/Hide</button>
          </li>

On click change it to true, makes it visible For Example in yout .ts file

showHide(item) {
    item.hidden = !item.hidden;
}