1

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.

Operator
  • 37
  • 5
  • 1
    you can add an extra property item.children.hide and toggle it by a click function and use it in
      . Please share a screenshot of your list and sublist
    – Dewanshu Jul 02 '20 at 10:14
  • Hey, thank you for your answer. The lists represents a directory so all ```
      ``` sublists are directories and all ```
    • ``` items represent the files of the directory and it works pretty well. I just have to add a toggle functionality for which I have no approach yet. I could add an extra property but if it is possible, I would like to do it without an extra property.
    – Operator Jul 02 '20 at 10:21

1 Answers1

1

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;
}
Usman Ali
  • 374
  • 1
  • 10
  • Hey, thank you for your answer. Would there be another approach without extending the object by a property of type boolean? – Operator Jul 02 '20 at 10:25
  • you can use this approach in Link https://toolset.com/forums/topic/javascript-to-hideshow-div-in-view-loop-item-targeting-first-result-only/#post-578599 but this is not angular approach – Usman Ali Jul 02 '20 at 10:31