单击外部关闭下拉菜单(Angular 4)

Edd*_*rro 1 javascript drop-down-menu typescript angular

所以我有一个输入:

<input id='search'placeholder="Search" formControlName='search'
       (click)="toggleDropDown()" type='text' novalidate>
Run Code Online (Sandbox Code Playgroud)

当你点击它时,它会显示一个“下拉”菜单:

<div *ngIf="showDropDown"
           class="search-bar-results">
        <li
          *ngFor="let x of searchItems | filter: getSearchValue()"
          (click)="selectValue(artist)">
            <img src="{{x.image}}"
                 alt="search result artist image"
                 class="search-bar-image">
            <p>{{x.name}}</p>
            <p>{{x.type}}</p>
        </li>
      </div>
Run Code Online (Sandbox Code Playgroud)

这是打字稿:

showDropDown = false;

toggleDropDown() {
    this.showDropDown = !this.showDropDown;
    console.log('clicked');
  }
Run Code Online (Sandbox Code Playgroud)

当用户点击输入时,下拉菜单会出现在 DOM / 屏幕上。到目前为止,我只能通过单击输入本身来关闭下拉菜单,但我正在尝试找到一种通过单击其他位置来关闭菜单的方法。

小智 5

参考blurAngular 2 on blur

与此相符的事情:

<input id='search'placeholder="Search" formControlName='search'
   (click)="toggleDropDown()" (blur)="closeDropDown()" type='text' novalidate>
Run Code Online (Sandbox Code Playgroud)

TS:

closeDropDown() {
    this.showDropDown = false;
    console.log('clicked outside');
}
Run Code Online (Sandbox Code Playgroud)