Search code examples
angularangular2-changedetection

Angular (click) not working after ngFor backing array updated


In the following Angular code, the click event does not fire after filteredList is updated:

<ul class="dropdown-menu" *ngIf="showOptions">
    <li *ngFor="let fund of filteredList" >
      <a (click)="selectFund(fund)">{{fund.name}}</a>
    </li>
</ul>

filteredList gets updated every time the user types something in a text input. Note that the text input is backed by a FormControl object, and filteredList gets updated when the FormControl.valueChanges observable sends new data.

The <a> tag list does get updated accordingly, so change detection happens as expected. The only issue is that clicks don't work anymore after every refresh.

The only way to make the (click) listener work again is to toggle showOptions to false then true through a UI click.

I must be missing something as this should work perfectly fine.

EDIT: You can see the code in action here: https://stackblitz.com/edit/angular-click-issue. Everything is in app.component.ts and app.component.html. If you select a dropdown element, it works. If you type a filter in the input, then click on a dropdown element, it does not work unless the dropdown gets closed and reopended.


Solution

  • The issue came from the following code (blur)="showOptions = false" on the input that updates the filteredList.

    Because of that code, I was trying to do something that was somewhat conflicting (hiding the options as I clicked on one of them), which lead to that side effect. I removed the (blur) binding and everything works fine!