ngFor 中的 Angular2 show/hide 下拉列表,并在其他任何地方单击时隐藏?

Angular2 show/hide dropdown in ngFor, and hide when clicked anywhere else?

我知道这个问题可能已经被问过上千次了,但我找不到 angular2 的任何正确解决方案。

所以我有一个 table 并且我正在为从服务器获取的每一行设置数据。因此我有一个 ngFor:

<table class="table table-hover mb-0 hidden-sm-down table-curved">
  <tbody>
    <tr *ngFor="let module of modules; let index = index" #moduleObject >
      <td class="text-center"><md-checkbox></md-checkbox></td>
        <td>
          <a class="test" (click)="module._clicked = !module._clicked"></a>
          <ul class="dropdown-menu table-dropdown" role="menu" [ngClass]="{'table-dropdown-open' : module._clicked}">
            <li><a (click)="_showDialogue =! _showDialogue; _getModuleCode(module)">Edit Module</a></li>
            <li><a (click)="removeModule(module.Code)" >Remove Module</a></li>
          </ul>
        </td>
    </tr>
  </tbody>
</table>

所以每一行看起来像这样:

而且我有一个切换功能,当你点击 3 个点时,它会显示一个下拉框,如下所示:

但是切换功能有两个问题,老实说我不知道​​如何解决:

1 - 当您点击 3 个点时,前两次点击有效,之后当您点击另一行的 3 个点时,它将无效(这意味着您必须双击才能显示下拉菜单。

2 - 目前我的切换效果仅在我必须单击 3 个点时才会发生,但我想实现这一点,当用户单击另一行的 3 个点时,显示在其他任何地方的下拉菜单会隐藏。当用户点击其他地方时,它也会隐藏其余的下拉菜单。

第二个对我来说很难,所以我有一个非常低效的隐藏下拉菜单的方法。

CloseAllDropDown() {
  //console.log(a)
  var dropdown = document.getElementsByClassName('table')[0].querySelectorAll('ul');
  for (let i = 0; i < dropdown.length; ++i) {
    document.getElementsByClassName('table-dropdown-open')[0].classList.remove('tabl‌​e-dropdown-open');
  }
}

如何实现以上两个列表?

更新

<tbody>
  <tr *ngFor="let module of modules; let index = index" #moduleObject >
    <td class="text-center"><md-checkbox></md-checkbox></td>
    <td (clickOutside)="visible = false">
      <a class="test" (click)="module._clicked = !module._clicked"></a>
      <ul class="dropdown-menu table-dropdown" role="menu" [ngClass]="{ 'table-dropdown-open' : module._clicked }" >
        <li><a (click)="_showDialogue =! _showDialogue; _getModuleCode(module)">Edit Module</a></li>
        <li><a (click)="removeModule(module.Code)" >Remove Module</a></li>
      </ul>
    </td>
  </tr>
</tbody>

您可以创建指令:

import {Directive, ElementRef, Output, EventEmitter, HostListener} from '@angular/core';

@Directive({
     selector: '[clickOutside]'
})
export class ClickOutsideDirective {
   constructor(private _elementRef: ElementRef) {}

@Output()
public clickOutside = new EventEmitter<MouseEvent>();

@HostListener('document:click', ['$event', '$event.target'])
public onClick(event: MouseEvent, targetElement: HTMLElement): void {
    if (!targetElement) {
        return;
    }

    const clickedInside = this._elementRef.nativeElement.contains(targetElement);
    if (!clickedInside) {
        this.clickOutside.emit(event);
    }
}}

然后你可以在你想要的地方调用它。例如:

<div (clickOutside)="visible = false"</div>