PrimeNG p-dropdown not taking custom default value

5k views Asked by At

I am using p-dropdown in my app and have noticed that after upgrading to PrimeNG 9 & Angular 10, the p-dropdown is no longer taking the custom value as the default value. Instead it takes the first value present in the options list as the default value. Further more the label now only fills half of the drop down while the reset is just empty. How can I fix this? Thanks in advance.

here is my template:

<div fxLayout="row" fxLayoutAlign="end center" fxLayoutGap="10px">
    <p-dropdown [options]="cityList" tooltipPosition="left" [(ngModel)]="selectedCity" optionLabel="label"></p-dropdown>
    <p-dropdown [options]="carList" tooltipPosition="left" [(ngModel)]="selectedCar" optionLabel="label"></p-dropdown>
    </p-button>
</div>

here is my ts code:

this.carList = [{ label: 'BMW', value: 'BMW' },{ label: 'Tesla', value: 'Tesla' },{ label: 'Toyota', value: 'Toyota' }];
this.cityList = [{ label: 'New York', value: 'New York' },{ label: 'Chicago', value: 'Chicago' },{ label: 'Boston', value: 'Boston' }];


this.selectedCity = { label: 'None', value: 'None' };
this.selectedCar = { label: 'None', value: 'None' };
2

There are 2 answers

0
Prajval Singh On

Dropdown selects the first option to be the default value, if you don't want this behaviour, you have to go with the placeholder, then the default value will not be the first option.

Also if you want to get just the value from the selected object you need to specify the optionValue parameter in the p-dropdown

code:

    <p-dropdown [options]="cityList" tooltipPosition="left" [(ngModel)]="selectedCity" optionLabel="label" optionValue="value"></p-dropdown>

Now here you may specify a different value as the answer(a value that does not exist in the options, that value will remain the value as long as its changed), which you can set as the default value

this.selectedValue = "None"

Checkout this demo Demo

0
PMO1948 On

In order for the dropdown to set the default to your custom value, your value must be part of the list. So, if you want to set it to 'none' originally, you need to have 'none' in the list. Note that your selectedCity and selectedCar should only be set to the values, not the selectItems. So you should just have selectedCity = 'None' etc.

If you do not want to add 'None' to your list, I suggest you use a placeholder instead - where you show the placeholder until a value has been selected