angularangular-materialmat-autocomplete

Angular Material Auto Complete Not Setting Selected when Filtered


I have come across an issue with the mat-autocomplete control for Angular Material where it does not add the CSS class "mdc-list-item--selected" to the mat-option and also doesn't add the mat-pseudo-checkbox to a selected option when the contents are displayed via an observable filtered array.

I've created a stackblitz where you can see the issue.

Mat-Autocomplete Stackblitz

The Filtered States Group does not show the selected option with a check and purple text but the Not Filtered States Group does. The ability for the user to see the selected option is important because they can modify the auto-complete after selecting a value to start a new search, however that doesn't actually change the selected value. So the visual indications for the selected option is very important for the usability.

Filtered States Group Not Filtered States Group

Does anyone see any issues with how this is configured in the stackblitz link or know of a work around?

I forked this stackblitz from the Angular Material's optgroup example that also has the same issue.


Solution

  • Many thanks to Yurii that responded to the issue that I created in the Angular Github with the following solution:

    As far as I can tell, the problem is not with the OptGroup component; rather, it is with the MatAutoComplete component, which does not handle a selection of selected mat-option like MatSelect does (At least I don't see that code)

    The way it works: Each mat-option holds a selected state and emits the event that the selection has been made. The MatAutoComplete does not listen to those changes and does not manage a selection state.

    In the example that you have provided, you are returning a brand-new object after the search .map((group) => ({ letter: group.letter, names: _filter(group.names, value), }))

    This code makes Angular to re-render the list which destroys mat-option instances that had the selected flag set to true and that is why you don't see the "highlighted" state.

    To fix your issue you could use a trackBy function *ngFor="let group of stateGroupOptions | async; trackBy: trackByFn"

    trackByFn = (_: number, item: StateGroup): string => { return item.letter; };