0

I am trying to create a searchable input with backend call. Instead of using datalist I would like to create custome UI with ul and li items. I am able to get the search functionality working but UI seems to be having glich I am trying to show ul when input focussed and but when try to use on blur of input to hide the ul when I do so before selecting the item in ul blur is fired and ul is hidden. What should be the right css for this case.

<input placeholder (blur)=“focussed=false” (focus)=“focussed=true” (keyup)=“filterData($event.target.value) ”/>
<ul *ngIf=“focussed”>
<li *ngFor=“item of filteredItems” >{{item}}</li>
</ul> 
Mahesh B
  • 143
  • 2
  • 13

1 Answers1

0

For item selection you can use (mousedown) instead of (click) as mousedown event has higher precedence over blur, mousedown event will get fired first

Assuming you have a selection handler for selecting list items, you can replace your li tag with

<li *ngFor="let item of filteredItems" (mousedown)="handleItemClick(item)">
     {{item}}
</li>

You can set focussed to false inside handleItemClick method which will close your list only after selection of item.

handleItemClick(item){
   // your code
   this.focussed = false; // to close the list
}
Shijil Narayanan
  • 1,011
  • 8
  • 21
  • Yes I have handleItemClick. Now the problem is if user wont select and moves away to another input element ul is still visible to user. Any way to handle this. – Mahesh B May 24 '20 at 09:32
  • The ul will get hidden when you click on a LI element, however if u don't click on the list element, your mouse cursor is still inside the input right, the moment you click outside anywhere on the page or any other element, it will trigger blur event which will hide your list as we are setting focussed to false on blur – Shijil Narayanan May 24 '20 at 12:11
  • Yes for the same reason I am looking for a solution that can be useful for both case. I mean instead of writing false case in blur is there any other methods I can use ? – Mahesh B May 25 '20 at 08:58
  • In order to close the list when clicked anywhere outside the list you can use any of the ways mentioned as a solution on this link https://stackoverflow.com/questions/35712379/how-can-i-close-a-dropdown-on-click-outside – Shijil Narayanan May 25 '20 at 09:07