2017-02-18 171 views
0

當我點擊一位家長時,所有的父母都會呈現他們的孩子,並且與隱藏相似。我是角2的新手。請推薦。Angular hide show not working

所以我有以下組成部分

import { Component, Input } from '@angular/core'; 

@Component({ 
    selector: 'sidebar-cmp', 
    templateUrl: 'sidebar.html', 
    styleUrls: [ 
     'sidebar.scss' 
    ] 
}) 

export class SidebarComponent { 
    @Input() tenants = 0; 
    showMenu: string = ''; 

    addExpandClass(element: any) { 
     if (element === this.showMenu) { 
      this.showMenu = '0'; 
     } else { 
      this.showMenu = element; 
     } 
    } 
} 

相應的HTML

<nav class="sidebar"> 
    <ul class="list-group" *ngFor="let tenant of tenants ;trackBy: trackId"> 
     <div class="nested-menu"> 
      <a class="list-group-item" (click)="addExpandClass('tenant.id')"> 
       <span><i class="fa fa-th-list"></i> &nbsp; {{tenant.name}}</span> 
      </a> 
      <li class="nested" [ngClass]="{'expand' : showMenu === 'tenant.id' }"> 
       <ul class="submenu"> 
        <li> 
         <a href><span>Submenu</span></a> 
        </li> 
        <li> 
         <a href><span>Submenu</span></a> 
        </li> 
       </ul> 
      </li> 
     </div>  
    </ul> 
</nav> 

enter image description here

+0

你的意思是這樣的[摺疊式菜單](http://bootsnipp.com/snippets/featured/accordion-menu) ? 一次只打開一個菜單的情況。 –

回答

0

它看起來像在這裏你傳遞字符串,而不是變量:

<a class="list-group-item" (click)="addExpandClass('tenant.id')"> 
     <span><i class="fa fa-th-list"></i> &nbsp; {{tenant.name}}</span> 
    </a> 

試試這個:

<a class="list-group-item" (click)="addExpandClass(tenant.id)"> 
     <span><i class="fa fa-th-list"></i> &nbsp; {{tenant.name}}</span> 
    </a> 

並據此:

<li class="nested" [ngClass]="{'expand' : showMenu === tenant.id }"> 
+0

謝謝。它現在有效 –

0
You are mistake in writing the [ngClass] 'tenant.id' is not a string. So why are pass as string. 

<nav class="sidebar"> 
    <ul class="list-group" *ngFor="let tenant of tenants ;trackBy: trackId"> 
     <div class="nested-menu"> 
      <a class="list-group-item" (click)="addExpandClass('tenant.id')"> 
       <span><i class="fa fa-th-list"></i> &nbsp; {{tenant.name}}</span> 
      </a> 
      <li class="nested" [ngClass]="{'expand' : showMenu === tenant.id }"> 
       <ul class="submenu"> 
        <li> 
         <a href><span>Submenu</span></a> 
        </li> 
        <li> 
         <a href><span>Submenu</span></a> 
        </li> 
       </ul> 
      </li> 
     </div>  
    </ul> 
</nav>