当 ngModel 变量是一个对象时,p-dropdown 不显示正确的标签

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

我正在使用 PrimeNG 的 p-dropdown 组件。当页面最初加载时,我正在设置 ng-model 但下拉列表始终将第一个元素显示为所选元素。

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'}}
        ];

此处 纽约 显示为下拉列表中的选定城市,即使我将 ng-model 更改为其他城市。

我认为您的问题出在 optionLabel="name" 中,因为您的城市对象不包含 name 键。

要么将其替换为 optionLabel="label",要么将城市对象从

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

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

StackBlitz