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?
[showClear]="true"
OR editable="true"
Please add showClear
property or editable property based on your requirement. This works perfectly for your use case
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With