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