Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feature(autocomplete): Add optionValue input #15309

Merged
merged 2 commits into from
Apr 26, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 16 additions & 3 deletions src/app/components/autocomplete/autocomplete.ts
Original file line number Diff line number Diff line change
Expand Up @@ -558,6 +558,11 @@ export class AutoComplete implements AfterViewChecked, AfterContentInit, OnDestr
* @group Props
*/
@Input() optionLabel: string | ((item: any) => string) | undefined;
/**
* Property name or getter function to use as the value of an option.
* @group Props
*/
@Input() optionValue: string | ((item: any) => string) | undefined;
/**
* Unique identifier of the component.
* @group Props
Expand Down Expand Up @@ -768,9 +773,13 @@ export class AutoComplete implements AfterViewChecked, AfterContentInit, OnDestr

inputValue = computed(() => {
const modelValue = this.modelValue();
const selectedOption = this.optionValueSelected
? (this.suggestions || []).find((item: any) => ObjectUtils.resolveFieldData(item, this.optionValue) === modelValue)
: modelValue;

if (modelValue) {
if (typeof modelValue === 'object') {
const label = this.getOptionLabel(modelValue);
if (typeof modelValue === 'object' || this.optionValueSelected) {
const label = this.getOptionLabel(selectedOption);

return label != null ? label : modelValue;
} else {
Expand Down Expand Up @@ -856,6 +865,10 @@ export class AutoComplete implements AfterViewChecked, AfterContentInit, OnDestr
return !this.virtualScroll;
}

get optionValueSelected() {
return typeof this.modelValue() === 'string' && this.optionValue;
}

constructor(@Inject(DOCUMENT) private document: Document, public el: ElementRef, public renderer: Renderer2, public cd: ChangeDetectorRef, public config: PrimeNGConfig, public overlayService: OverlayService, private zone: NgZone) {
effect(() => {
this.filled = ObjectUtils.isNotEmpty(this.modelValue());
Expand Down Expand Up @@ -1564,7 +1577,7 @@ export class AutoComplete implements AfterViewChecked, AfterContentInit, OnDestr
}

getOptionValue(option) {
return option; // TODO: The 'optionValue' properties can be added.
return this.optionValue ? ObjectUtils.resolveFieldData(option, this.optionValue) : option && option.value != undefined ? option.value : option;
}

getOptionIndex(index, scrollerOptions) {
Expand Down