p-dropdown does not display correct label when ngModel variable is an object
Asked Answered
M

1

6

I am using PrimeNG's p-dropdown component. When the page loads initially I am setting the ng-model but the drop down shows first element as the selected element always.

HTML

<p-dropdown [options]="cities" [(ngModel)]="selectedCity"  optionLabel="name" [showClear]="true"></p-dropdown>
<p>Selected City: {{selectedCity ? selectedCity.name : 'none'}}</p>

TS

this.cities = [
            {label:'New York', value:{id:1, name: 'New York', code: 'NY'}},
            {label:'Rome', value:{id:2, name: 'Rome', code: 'RM'}},
            {label:'London', value:{id:3, name: 'London', code: 'LDN'}},
            {label:'Istanbul', value:{id:4, name: 'Istanbul', code: 'IST'}},
            {label:'Paris', value:{id:5, name: 'Paris', code: 'PRS'}}
        ];

Here New York is shown as the selected one in the dropdown even if I change the ng-model to some other city.

Merlon answered 15/5, 2018 at 9:18 Comment(0)
U
3

I think your problem is in optionLabel="name" because your city object does not contain a name key.

Either you replace it with optionLabel="label" or you change your city object from

{label:'New York', value:{id:1, name: 'New York', code: 'NY'}}

to

{name:'New York', value:{id:1, name: 'New York', code: 'NY'}}

See StackBlitz

Unstrap answered 15/5, 2018 at 11:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.