PrimeNg DropDown - User can't clear the value

Deadly 提交于 2019-12-10 08:12:46

问题


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?


回答1:


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.




回答2:


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.




回答3:


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




回答4:


Since the component is not allowing reset value function, I have implemented a button in the form the clear all the values...

It works properly



来源:https://stackoverflow.com/questions/44287700/primeng-dropdown-user-cant-clear-the-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!