2017-02-25 41 views
0

我有一個使用ngFor的表格中顯示的項目列表,每個項目都有一個相應的下拉框,僅當您點擊該項目時纔會顯示。問題是,我只想顯示被點擊的下拉框,並隱藏之前打開的其他項目的下拉框。目前,我可以打開多個項目的下拉框。但是,我只想顯示點擊項目的下拉菜單。例如:如何在Angular2的`ngFor`中只顯示單擊元素的下拉菜單?

enter image description here

但是我想的是,當我點擊不同的項目,我希望所有的下拉菜單隱藏,只顯示當前點擊一個。

這是可能做angular2?

我有一個指令,查找點擊事件,並觸發他們,這只是用來顯示/隱藏,但我不知道如何解決我的問題,目前的:

這裏是我的代碼:

// assume necessary imports {..}... 
 
@Directive({ 
 
    selector: '[rbDropdown]' 
 
}) 
 
export class NgDropdownDirective { 
 
    constructor(private _ref: ElementRef) {} 
 

 
    @HostBinding('class.open') get opened() { 
 
    return this.isOpen; 
 
    } 
 

 
    @HostListener('click', ['$event', '$event.target']) open() { 
 
    console.log(this._ref.nativeElement); 
 
    //this._ref.nativeElement.children[1].classList.add('table-dropdown-open'); 
 
    if (this._ref.nativeElement.children[1].classList.contains('table-dropdown-open')) { 
 
     this._ref.nativeElement.children[1].classList.remove('table-dropdown-open'); 
 
     this.isOpen = false; 
 
    } else { 
 
     this.isOpen = true; 
 
     this._ref.nativeElement.children[1].classList.add('table-dropdown-open'); 
 
    } 
 
    } 
 
    private isOpen = false; 
 
}

這是我ngFor對於我的項目:

<tbody> 
 
    <tr *ngFor="let module of modules"> 
 
    <td class="text-center"> 
 
     <md-checkbox></md-checkbox> 
 
    </td> 
 
    <td> 
 
     <div><span class="title-Code">{{module.Code}}</span></div> 
 
     <div class="small text-muted"><span>{{module.Name}}</span></div> 
 
    </td> 
 
    <td>{{ module.Credit}}</td> 
 
    <td>{{ module.Structure }}</td> 
 
    <td>{{ module.Tags }}</td> 
 
    <td>{{ module.LastEdit }}</td> 
 
    <td rbDropdown> 
 
     <a class="test" #thisTag></a> 
 
     <ul class="dropdown-menu table-dropdown" role="menu"> 
 
     <li> 
 
      <a (click)="_showDialogue =! _showDialogue; _getModuleCode(module)"><img src="../../assets/img/pencil.svg" alt="" width="13px">Edit Module</a> 
 
     </li> 
 
     <li> 
 
      <a (click)="removeModule(module.Code)"><img src="../../assets/img/delete.svg" alt="" width="13px">Remove Module</a> 
 
     </li> 
 
     </ul> 
 
    </td> 
 
    </tr> 
 
</tbody>

對不起,我不知道如何使用plunker顯示我的問題。

您的幫助將非常感謝這個美好的社區!

+0

歸納您​​的問題 - 你有幾個投寄箱,你想隱藏他們每個人的期望點擊一個? –

+0

我對每一行都有一個下拉框,但它們最初是隱藏的,只有在您點擊它們時纔可見。但目前我可以顯示多個項目的下拉框,並且如果我點擊另一個項目,它們仍然保持打開狀態,但回答您的問題?是@Kinduser – DingDong

回答

0

爲簡單起見我用下面的模板

<div *ngFor="let item of data"> 
    {{id}} &nbsp; &nbsp; &nbsp; &nbsp; 
    <button (click)="showItems($event)"> {{item.class}} </button> 
    <students style="visibility:hidden" [studentsList]="item.studentsList"> </students> 
</div> 

學生組件將看起來如下

<div *ngFor="let item of studentsList"> 
      {{item.id}} &nbsp; &nbsp; &nbsp; &nbsp; 
       <button> {{item.name}} </button> 
</div> 

方法

showItems(val){ 

    val.srcElement.nextElementSibling.style['visibility']="visible"; 

} 

此方法將如果切換相應的元件,層次結構如下

LIVE DEMO

相關問題