简体   繁体   中英

Angular 5 - ngFor with pipe and on click event

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) .

在此处输入图片说明

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM