Angular search box needs to disappear when user clicks outside the search box

Viewed 950

I am making an application in Angular (4) that contains a searchbox. When a user searches, the searching variable turns true. When a user clicks outside of the searchbox, this variable needs to turn to false.

I have gotton this to work with the (blur) and (focus) attributes:

<mat-form-field class="full-width">
  <input matInput #searchBox (blur)="searching = false" (focus)="searching = true" placeholder="{{ placeHolder }}" autocomplete="off" (keyup)=search(searchBox.value) />
</mat-form-field>
<div class="dropdown">
    <ul [hidden]="!searching">
      <li (click)="outputProduct(product1)"> Option 1 </li>
      <li (click)="outputProduct(product2)"> Option 2 </li>
    </ul>
</div>

The problem however now is that, if a user clicks on one of the search results, the outputProduct(product) function is now not called. This is probably because the [hidden] attribute prevents the click event to reach my list item. What would be the correct way to implement this functionality?

1 Answers

Try by adding another boolean variable to check whether there is a focus on the list results or not.

app.component.ts

export class AppComponent  {
  ...
  searching = false;
  focusOnList = true;
}

app.component.html

<div (mouseout)="focusOnList=false">
<mat-form-field class="full-width">
  <input matInput #searchBox (blur)="searching=false" (focus)="searching = true" placeholder="{{ placeHolder }}" autocomplete="off" (keyup)=search(searchBox.value) />
</mat-form-field>
<div *ngIf="searching || focusOnList" class="dropdown" (mouseover)="focusOnList=true" (focus)="focusOnList=true">
    <ul>
      <li (click)="outputProduct(product1)"> Option 1 </li>
      <li (click)="outputProduct(product2)"> Option 2 </li>
    </ul>
</div>
</div>

Here the variable focusOnList is set to false when you focus out of the whole div. And you show the list if you are searching OR if the mouse is over the list.

Related