简体   繁体   English

输入字段处于活动状态时单击事件未触发

[英]Click event not firing when input field is active

I have an Angular project with a setup similar to this:我有一个 Angular 项目,其设置类似于:

<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.有一个用户输入的输入字段。当他们输入时, item-list组件会填充结果。

In the item list component, it simply shows all items passed in, and if one is clicked, it fires the event itemClick在项目列表组件中,它只是显示所有传入的项目,如果单击一个,它会触发事件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.第一次单击仅触发ngModelChange事件,第二次单击触发itemClick事件。

Update:更新:

This apparently has something to do with the structure of the app-iutem-list component.这显然与app-iutem-list组件的结构有关。 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.我添加了 2 个按钮,它们只是写入控制台。 Button #1 works even if the input is still active, button #2 does not.即使输入仍然处于活动状态,按钮 #1 也可以工作,而按钮 #2 则不能。

click is a DOM event, not related to the higher level ngModel. click 是一个 DOM 事件,与更高级别的 ngModel 无关。 The proper event for this is ngModelChange正确的事件是 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.单击其中一个项目时,ngModel 将触发一个更改事件,这将更改项目列表。 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.新的项目列表将被传递给item-list组件,在那里它将删除/更新整个列表并错过点击事件。

Adding a trackBy to the *ngFor to prevent unnecessary updates fixed the issue.trackBy添加到*ngFor以防止不必要的更新解决了该问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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