简体   繁体   中英

Angular 4 hide/show using ng-container

Having an issue showing and hiding list items using ng-container. When I select a list item to show sub item lists it returns all sub item lists and not just the selected one.

List1 (Selected)
-item1
-item2

List2 (not selected but still showing items when List1 is selected and vice versa)
-item1
-item2

HTML

<ul class="side-nav" *ngFor="let sideNavMenuItem of sideNavMenuItems;">

    <ng-container>
      <li *ngIf="sideNavMenuItem.subMenu">
        <a id="link" routerLink="{{ sideNavMenuItem.url }}">

          <i class="menu-icon fa {{ sideNavMenuItem.menuIcon }}" aria-hidden="true">
          </i> <span class="menu-name" (click)="toggle()" id="bt">{{ sideNavMenuItem.menuName }}</span>

          <ul *ngFor="let subMenu of sideNavMenuItem.subMenu">
            <li *ngIf="show"><a routerLink="{{ subMenu.url }}">{{ subMenu.menuName}}</a>
            </li>
          </ul>

        </a>
      </li>
    </ng-container>
  </ul>

Component

toggle() {
    this.show = !this.show;
  }

Change show to array of Boolean instead of one value to all objects.
and add index to the *ngFor:

<ul class="side-nav" *ngFor="let sideNavMenuItem of sideNavMenuItems; let i = index">

on the click event, add the index of the object:

<span class="menu-name" (click)="toggle(i)" id="bt">{{ sideNavMenuItem.menuName }}</span>

and change the toggle function to:

toggle(index) {
  this.show[index] = !this.show[index];
}

and last thing in the *ngIf add the index in the show array

<li *ngIf="show[i]">
  <a routerLink="{{ subMenu.url }}">{{ subMenu.menuName}}</a>
</li>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM