user3640967
user3640967

Reputation: 538

Detect if element has focus in Angular2

I am displaying an autocomplete dropdown for a text input using (focus)="showSearchList=true" on the input, and hiding it again using (blur)="showSearchList=false".

My problem is that if one of the results in the dropdown is clicked I want to trigger another method, but by clicking the element in the dropdown I am triggering the blur method of the input, so the dropdown results do not get clicked. What is the best way to make this work? I am using ES6, not Typescript, and am struggling to find anything on Google.

This is the template I have so far:

<div id="searchContainer">
    <input [(ngModel)]="search"
           (ngModelChange)="filterSearch()"
           (focus)="showSearchList=true;"
           (blur)="showSearchList=false"
           type="text"
           id="searchJobs"
           placeholder=" Search"/>
    <div *ngIf="showSearchList"
         id="searchDropdown">
        <p *ngFor="let result of filteredSearchResults; let index = index;"
            (click)="addResultToResults(index); search='';">
            {{result}}
        </p>
    </div>
</div>

I thought instead of setting showSearchList to false on blur, I could call a method instead that checks which element has focus, and depending on that either hide the dropdown, or run my addResultToResults method and then hide the dropdown, but I have no idea how to check which element has focus in angular2.

Would love some feedback on this!

Upvotes: 5

Views: 10711

Answers (1)

Pengyy
Pengyy

Reputation: 38171

I would recommend using mouseleave event to control searchlist and move blur event from input element. And if you want to show after click items in searchlist, you can combine with click event.

Plunker demo.

Upvotes: 2

Related Questions