如何在 angular 2 和 primeng 中为下拉多选设置默认值

How to set default value for drop-down multiselect in angular 2 and ngprime

我正在关注 PrimeNg Example .and here is a Plunker。如何在下拉列表中预先选择一些值。

  <p-multiSelect [options]="cities" [(ngModel)]="selectedCities"></p-multiSelect>

所选城市存储在selectedCities数组中。由于它是双向绑定,只需填充那个数组,它就会反映在视图中。

import {SelectItem} from 'primeng/primeng';

let cities: SelectItem[] = [
    { label : "Rome"     , value : "ro" },
    { label : "London"   , value : "lo" },
    { label : "Paris"    , value : "pa" },
    { label : "New York" , value : "ny" }
]

let selectedCities: string[] = ["lo", "ny"] // This will pre-select the cities in your dropdown

您只需将 数组 值附加到 selectedCities 变量,以便将其绑定到 模型。

在您的例子中, 属性 是一个包含许多属性的 object

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

解决方法是map数组项,以获得你想要的值。

例如,这将从您的 dropdown 元素中预选第一个 two items

this.selectedCities = this.cities.slice(0,2).map(a => a.value));

如果您想从 given 数组中预选值,您应该使用 filter 方法。

let arrayOfValues=['NY','IST'];
this.selectedCities = this.cities.filter(a => arrayOfValues.includes(a.value.cityCode)).map(a => a.value));

有个好办法 您可以为每个选项定义价值。 然后将变量 selectedCities 定义为您想要的默认值。 这将使 angular 在初始化时选择该值选项。

let Cities: SelectItem[] = [
    { label : "Rome"     , value : "ro" },
    { label : "London"   , value : "lo" },
    { label : "Paris"    , value : "pa" },
    { label : "New York" , value : "ny" }
]

selectedCity = "ro";

这会将选定的值设置为默认的罗马。

(*感谢 Jeremy Thille。我从您那里复制了一部分代码。)