Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect Input Focus Using Angular 2+

I'm trying to create an auto-complete list that appears as you type, but disappears when you click elsewhere on the document. How do I detect that a form input is focused using Angular 2. Angular 1 has ng-focus, but I don't think Angular 2 supports that anymore.

<input id="search-box" type="search" class="form-control [(ngModel)]=query (keyup)=filter()>     <div id="search-autocomplete" *ngIf="filteredList.length > 0">         <ul *ngFor="#item of filteredList" >             <li > <a (click)="select(item)">{{item}}</a> </li>         </ul>     </div> 

By the way, I used this tutorial as guidance.

like image 214
wpakt Avatar asked Apr 20 '16 21:04

wpakt


People also ask

How does angular detect focus?

hasFocus() : whether the document or any element inside the document has focus. document. activeElement : Property containing which element currently has focus.

How do you know if input field has focus?

HTML DOM Document hasFocus() The hasFocus() method returns a true if the document (or any element in the document) has focus. Otherwise it returns false .

What is Focus event in angular?

The ng-focus directive tells AngularJS what to do when an HTML element gets focus. The ng-focus directive from AngularJS will not override the element's original onfocus event, both will be executed.


1 Answers

There are focus and blur events:

<input (blur)="onBlur()" (focus)="onFocus()"> 
like image 177
kemsky Avatar answered Oct 21 '22 17:10

kemsky