I have an Angular project with a setup similar to this:
<input type="text" [(ngModel)]="search" >
<app-item-list
[items]="foundItems"
(itemClick)="onItemSelected($event)">
</app-item-list>
There's an input field that the user types in. As they type, the item-list
component populates with results.
In the item list component, it simply shows all items passed in, and if one is clicked, it fires the event itemClick
So long as the input remains active, the user must click twice on an item in order for the click event to fire. Clicking anywhere else (to deselect the input field) and then clicking an item also works.
This is supposed to be some sort of search 'dropdown box', where typing displays a list of autocomplete-like options fetched from elsewhere. It works fine other than having to click twice. The first click only fires an ngModelChange
event and the second fires the itemClick
event.
Update:
This apparently has something to do with the structure of the app-iutem-list
component.
This is a look inside:
<button (click)="clickLog(1)"></button>
<ul>
<li *ngFor="let item of items; let i = index" (click)="onItemClicked(i)">
<button (click)="clickLog(2)"></button>
<b >{{ item.title }}</b>
<div >{{ item.subtitle }}</div>
</li>
</ul>
I have added 2 buttons which simply write to the console. Button #1 works even if the input is still active, button #2 does not.
CodePudding user response:
click is a DOM event, not related to the higher level ngModel. The proper event for this is ngModelChange
<input type="text" [(ngModel)]="search" >
<app-item-list
[items]="foundItems"
(ngModelChange)="onItemSelected($event)">
</app-item-list>
CodePudding user response:
This ended up being an issue with the list items updating at the exact moment of the first click.
On clicking one of the items, ngModel would fire a change event, which would alter the item list. The new item list would be passed down to the item-list
component, where it would remove/update the entire list and miss the click event.
Adding a trackBy
to the *ngFor
to prevent unnecessary updates fixed the issue.