简体   繁体   中英

Click event not firing when input field is active

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 class="title">{{ item.title }}</b>
        <div class="subtitle">{{ 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.

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>

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.

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