Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PrimeNg DropDown - User can't clear the value

I'm implementing primeNg dropdown component in my Angular2 application.

<p-dropdown [options]="listCustomers_itm" placeholder="Selezionare" [(ngModel)]="Customer_itm" [ngModelOptions]="{standalone: true}" [style]="{'width':'225px'}" filter="filter"  (onChange)="onCustomerSelect($event.value)">
</p-dropdown>

All works fine except one annoing thing:

Once time the user has selected an option, he can't clear the selected value...

Can you help me?

like image 658
DarioN1 Avatar asked May 31 '17 14:05

DarioN1


3 Answers

[showClear]="true" OR editable="true" Please add showClear property or editable property based on your requirement. This works perfectly for your use case

like image 188
user2566954 Avatar answered Oct 01 '22 05:10

user2566954


To clear the selected dropdown value, just set the selected option to an empty string. For example, here's a drop-down that let's the user select "Last Month" or "Last Week:"

Component

ngOnInit() {
    // Initialize drop-down values
    this.ranges = [];
    this.ranges.push({label: 'Last Month', value: 'Last Month'});
    this.ranges.push({label: 'Last Week', value: 'Last Week'});
}

clearDropDown = () => {
  this.selectedRange = '';
};

Template:

<p-dropdown 
    [options]="ranges" 
    [(ngModel)]="selectedRange" 
    placeholder="Select a Date Range">
</p-dropdown>

<button (click)="clearDropDown()">Clear Date Range</button>

If 'Last Month' is currently selected in the dropdown, clicking the button will clear the dropdown value (and 'Select a Date Range' will once again be shown).

PS: In this example, 'Select a Date Range' is placeholder text. It is not a selectable option from the dropdown. In most cases, this is what you want.

like image 29
Stevethemacguy Avatar answered Oct 01 '22 05:10

Stevethemacguy


To fix this, I had to set a placeholder for the dropdown. The code I used is something like:

template.html

<p-dropdown ...
            placeholder="Select"
            #dropDownThing></p-dropdown>

<button (click)="onButtonClick()"></button>

component.ts

import { Dropdown } from "primeng/components/dropdown/dropdown";
...
@ViewChild('dropDownThing')
dropDownThing: Dropdown;
...
onButtonClick() {
    this.dropDownThing.value = <someValueNotInTheDropdown'sList>;
}
...

When the code above is run without a placeholder, the currently-selected option remains selected.

When the code above is run with a placeholder, the dropdown's value changes to the provided placeholder.

like image 21
Daniel Neel Avatar answered Oct 01 '22 05:10

Daniel Neel