I'm using PrimeNG in my Angular project, and I have a (Dropdown) component. I want to implement a feature where if a user clicks on the already selected item, the selected value should be cleared.
Expected Behavior:
- When a user selects an item, it should be set as the selected value.
- If the user clicks again on the same selected item, the selection should be cleared (set to null or an empty value).
How can I modify the PrimeNG p-dropdown component so that clicking the already selected option clears the selected value? Is there any workaround or built-in feature without using [showclear] for this?
I appreciate any help!
<p-select [options]="difficulty" [(ngModel)]="selectedDifficulty" optionLabel="name" placeholder="Difficulty"
class="w-full md:w-33" />
I'm using PrimeNG in my Angular project, and I have a (Dropdown) component. I want to implement a feature where if a user clicks on the already selected item, the selected value should be cleared.
Expected Behavior:
- When a user selects an item, it should be set as the selected value.
- If the user clicks again on the same selected item, the selection should be cleared (set to null or an empty value).
How can I modify the PrimeNG p-dropdown component so that clicking the already selected option clears the selected value? Is there any workaround or built-in feature without using [showclear] for this?
I appreciate any help!
<p-select [options]="difficulty" [(ngModel)]="selectedDifficulty" optionLabel="name" placeholder="Difficulty"
class="w-full md:w-33" />
Share
Improve this question
edited Feb 7 at 20:01
Murad
asked Feb 7 at 19:53
MuradMurad
626 bronze badges
1 Answer
Reset to default 1From the p-select
onOptionClick
method, it only handles the option not previously selected.
But you can overwrite the default behavior for onOptionClick
to de-select the selected option.
import { ViewChild } from '@angular/core';
import { Select } from 'primeng/select';
@ViewChild(Select) mySelect: Select;
ngAfterViewInit() {
this.mySelect.onOptionSelect = (
event,
option,
isHide = true,
preventChange = false
) => {
if (!this.mySelect.isSelected(option)) {
const value = this.mySelect.getOptionValue(option);
this.mySelect.updateModel(value, event);
this.mySelect.focusedOptionIndex.set(
this.mySelect.findSelectedOptionIndex()
);
preventChange === false &&
this.mySelect.onChange.emit({ originalEvent: event, value: value });
} else {
this.mySelect.clear();
}
if (isHide) {
this.mySelect.hide(true);
}
};
}
Demo @ StackBlitz