Search code examples
angularngforvmware-clarity

Input loses focus when filtering an array, rendered using *ngFor and Clarity's Angular components


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.


Solution

  • 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