'Angular mat-autocomplete: Setting active item programmatically
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
Steps to reproduce:
- Click on the input.
- Click on
Show More
. - SetActiveItem selects the item at specified index but changing selection afterward is broken.
- Navigate to
Show More
with the keyboard. - Press Enter.
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.
Solution 1:[1]
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?
Solution 2:[2]
I had to use setTimeout. The fix was:
setTimeout(() => {
this.matSelect._keyManager.setActiveItem(1);
this.matSelect._keyManager.setActiveItem(2);
}, 1);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | JuNe |
Solution 2 |