Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 641
user3640967 Avatar asked Oct 30 '22 07:10

user3640967


1 Answers

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.

like image 80
Pengyy Avatar answered Nov 15 '22 05:11

Pengyy