-
Notifications
You must be signed in to change notification settings - Fork 5k
Description
Describe the bug
For AutoComplete components, we can use optionLabel to display a custom label in the suggestions and selected item.
This works fine when the suggestions are objects but it does not work properly when the suggestions are just strings. In that case, the selected item does not display the label provided by optionLabel but just the value itself, while with objects, the selected item displays the label generated by optionLabel.
Edit:
After some initial investigation of the source code, I saw in
primeng/packages/primeng/src/autocomplete/autocomplete.ts
Lines 860 to 875 in 993680d
| inputValue = computed(() => { | |
| const modelValue = this.modelValue(); | |
| const selectedOption = this.optionValueSelected ? (this.suggestions || []).find((option: any) => equals(option, modelValue, this.equalityKey())) : modelValue; | |
| if (isNotEmpty(modelValue)) { | |
| if (typeof modelValue === 'object' || this.optionValueSelected) { | |
| const label = this.getOptionLabel(selectedOption); | |
| return label != null ? label : modelValue; | |
| } else { | |
| return modelValue; | |
| } | |
| } else { | |
| return ''; | |
| } | |
| }); |
primeng/packages/primeng/src/autocomplete/autocomplete.ts
Lines 921 to 923 in 993680d
| get optionValueSelected() { | |
| return typeof this.modelValue() === 'string' && this.optionValue; | |
| } |
optionLabel is only applied to the selected item if the value is an object or if it's a string and the optionValue property is set.But this does not really make sense to me since why would you set
optionValue if the value is a string??I think the logic in the
inputValue signal computation is flawed. In my opinion, optionLabel should always be applied, no matter the type of the value.
So, apparently there is a workaround to fix this issue: Add an optionValue function that just returns the item itself, aka:
optionValue(item: any): any {
return item;
}Pull Request Link
Reproducer
https://stackblitz.com/edit/dz8njim1-jg7bfq1g?file=src%2Fapp%2Fautocomplete-objects-demo.html
Environment
PrimeNG 20.3.0, Angular 20, Firefox
Angular version
20.0.4
PrimeNG version
v20
Browser(s)
Firefox
Steps to reproduce the behavior
- Go to https://stackblitz.com/edit/dz8njim1-jg7bfq1g?file=src%2Fapp%2Fautocomplete-objects-demo.html
- The top AutoComplete uses an array of objects for the suggestions, while the bottom AutoComplete uses an array of strings
- The optionLabel function is the same for both and just returns
test - When we select and item in both AutoCompletes, the top one still displays
test(which is intended behaviour) while the bottom one displays the actual value instead oftest
Expected behavior
The selected item in AutoCopmlete component should always display the label generated by optionLabel no matter if the suggestions are objects or primitive types like strings.