最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

angular - How to Clear p-select Value When Clicking on the Selected Item in PrimeNG? - Stack Overflow

programmeradmin2浏览0评论

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
Add a comment  | 

1 Answer 1

Reset to default 1

From 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

发布评论

评论列表(0)

  1. 暂无评论