You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在更新数据时为PrimeNG p-dropdown设置选中值

解决方案

PrimeNG的p-dropdown是靠ngModel绑定的值来决定选中哪一项的,options数组里的selected属性不会自动同步到ngModel,得手动把选中项的value赋值给绑定的变量才行。

先修正模板的语法错误

你的模板代码里[(ngModel)]="category少了闭合引号,先改对:

<p-dropdown name="category" [options]="Category" [(ngModel)]="category"></p-dropdown>

数据更新后设置默认选中

等你的Category数据更新完(比如从接口拿到新数据),找到数组里selected: true的那一项,把它的value赋值给category变量就搞定了:

// 举个例子,假设这是你更新Category数据的逻辑
this.Category = [
  {disabled: false, group: null, selected: false, text: 'Laptop', value: '2'},
  {disabled: false, group: null, selected: true, text: 'Desktop', value: '1'}
];

// 筛选出selected为true的项
const defaultSelectedItem = this.Category.find(item => item.selected);
if (defaultSelectedItem) {
  this.category = defaultSelectedItem.value; // 把对应value赋值给ngModel绑定的变量
}

注意点

  • 如果是异步加载数据(比如发HTTP请求拿数据),一定要等Category完全加载好再执行上面的赋值逻辑,不然可能找不到目标项。
  • 要是想每次Category更新都自动同步选中项,可以把赋值逻辑写到Category的setter里,或者放在数据更新的回调函数里。

内容的提问来源于stack exchange,提问作者Ghayoor Balti

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 04:00:20