3

What are you trying to do?

Setting an item in my panel active programmatically.

What are you seeing that does not match your expectations?

Using autocomplete's keymanager function setActiveItem doesn't actually update the visuals of the panel at all. When triggering a visual update manually it works on mouse-click but not when navigating with the keyboard.

Reproduction

StackBlitz demo

Steps to reproduce:

  1. Click on the input.
  2. Click on Show More.
  3. SetActiveItem selects the item at specified index but changing selection afterward is broken.
  4. Navigate to Show More with the keyboard.
  5. Press Enter.
  6. SetActiveItem doesn't work at all.

Environment

  • Angular: 8.2.8
  • CDK/Material: 8.2.2
  • Browser(s): All of them
  • Operating System (e.g. Windows, macOS, Ubuntu): All of them

Looking for tips on how to get this working. Is my approach wrong or does setActiveItem not work the way it should? In the function annotations, it is described as:

Sets the active item to the item to the specified one and adds the active styles to it. Also removes active styles from the previously active item.

That sounds like the exact functionality I need but I can't get it to work.

nash11
  • 8,220
  • 3
  • 19
  • 55

2 Answers2

0

I had a similar problem. In my case I used Ag-Grid and that stopped the event propagation of the navigation with the arrows. Are you sure your Mat-Autocomplete recieves the event?

JuNe
  • 1,911
  • 9
  • 28
  • I'm not sure, but I just use a slightly modified version of the Autocomplete overview example on https://material.angular.io/components/autocomplete/examples to showcase the "Show More" use case in my StackBlitz demo. No other libraries that could interfere. – Christian Moll Oct 01 '19 at 11:17
  • replace for work around in "showMore" function: this.autoComplete._keyManager.setActiveItem(1); --> this.autoComplete.autoActiveFirstOption = true; – JuNe Oct 01 '19 at 11:36
  • That one interestingly breaks when using mouse click on "Show More". I found out that the reason my example doesn't work at all with keyboard navigation is that the _handleKeydown function of autocomplete-trigger.ts always resets the active item after running the selection logic. – Christian Moll Oct 01 '19 at 12:14
0

I had to use setTimeout. The fix was:

setTimeout(() => {
     this.matSelect._keyManager.setActiveItem(1);
     this.matSelect._keyManager.setActiveItem(2);
}, 1);
roniccolo
  • 99
  • 1
  • 5