简体   繁体   English

使用ng-container进行Angular 4隐藏/显示

[英]Angular 4 hide/show using ng-container

Having an issue showing and hiding list items using ng-container. 使用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 的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. 将show更改为Boolean数组,而不是所有对象的一个​​值。
and add index to the *ngFor: 并将索引添加到* ngFor:

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

on the click event, add the index of the object: 在click事件上,添加对象的索引:

<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 * ngIf的最后一件事如果在show数组中添加索引

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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