1

I have a list of users rendered using *ngFor. The user has the option to filter the list by typing the name in the input field.

However, when the user starts typing to filter, the input field loses focus as soon as the list starts to filter down. Following a few different posts here on stackoverflow (1, 2, 3), I have used trackBy function in the *ngFor to allow Angular to uniquely identify items and perform DOM updates as needed.

The Angular docs describes that trackBy function is important to "preserve any DOM-specific UI state (like cursor position, focus, text selection) when the iterable is modified". But in my case, this UI state of focus is lost when the array is modified.

Here is a link to a reproducible scenario in stackblitz. The problem description and steps to reproduce are also described there.

Manish Shrestha
  • 411
  • 8
  • 12

1 Answers1

1

trackBy is perfectly fine while the issue is with clrDropdownItem directive applied to <li> which was not required. This directive auto gains the focus to the first element as soon as list is updated. I just removed it and now your code is working fine.

Here is a link with working code - https://stackblitz.com/edit/clarity-dark-theme-v5-cat3jm?devtoolsheight=33&file=src%2Fapp%2Fapp.component.html

Suneet Bansal
  • 2,664
  • 1
  • 14
  • 18
  • Thanks for giving it a go Suneet. Removing the `clrDropdownItem` certainly fixed the issue of losing focus but now, clicking on the user no longer closes the dropdown menu. As an extension to your suggestion, wrapping the 2 divs containing user's name and email with an outer div, with the `clrDropdownItem` directive and click event certainly works. [Link to fix](https://stackblitz.com/edit/clarity-dark-theme-v5-sjkqij?file=src/app/app.component.html). For future readers, this does need styling fixes and keyboard navigation no longer works. But that's okay for me currently. – Manish Shrestha Jan 06 '22 at 11:39