Angular 5 - ngFor with pipe and on click event

2k views Asked by At

I loop through an array of objects with *ngFor and apply a couple of pipes which filter the resulting list. One of the pipes uses a user input from a search field. When a user clicks one of the ngFor elements, the object is sent to a function and added to a "selection" array, to be used later.

<input type="search" [(ngModel)]="searchInput"> 
<a *ngFor="let item of items | firstFilter | inputFilter:searchInput; let i = index">
 <span (click)="send(item)"> send {{item.name}} </span>
</a>

I am trying to replicate the behaviour of a search field (like google) where the first result is highlighted and if the user presses enter while typing, it would trigger the same action as clicking on the result send(item).

enter image description here

Highlighting is easy enough with ngClass checking if the input is not empty and i === 0.

What I got stuck with is the enter key press event.

  • How would I listen to the event in the input field, from inside the ngFor loop, and only for the first result (i===0) ?
  • Is there a way to record the list of objects (or at least the first one), after the pipes have been applied to the items array?
  • How would you suggest to go about this?
1

There are 1 answers

4
Mac_W On

Try this:

<input 
    type="search" 
    [(ngModel)]="searchInput"
    (keyup.enter)="selectFirstElement()"> 
<a *ngFor="let item of items | firstFilter | inputFilter:searchInput; let i = index">
 <span 
    (click)="send(item)"> send {{item.name}} </span>
</a>

Add a method selectFirstElement which will access the first element or the one which is highlighted when the user presses enter.