如何在角度2和ngprime中设置下拉多选的默认值
问题描述:
我在关注PrimeNg Example。这里是一个Plunker。如何在下拉菜单中预先选择一些值。如何在角度2和ngprime中设置下拉多选的默认值
<p-multiSelect [options]="cities" [(ngModel)]="selectedCities"></p-multiSelect>
答
你只需要值的阵列重视selectedCities
变量,以结合这给模型。
在你的情况下,值属性是一个object
其中包含许多属性。
value:{id:1, name: 'New York', cityCode: 'NY'}
的解决方案是map
阵列项目,以获得您想要的值。
例如,这会从你的下拉元素预选拳头 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));
完整示例here。
答
选定的城市存储在selectedCities
数组中。由于它是双向绑定,只需填充该arry,它就会反映在视图中。
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定义为您想要的值为defult。 它会使初始化时选择该VAL选项的角度。
let Cities: SelectItem[] = [
{ label : "Rome" , value : "ro" },
{ label : "London" , value : "lo" },
{ label : "Paris" , value : "pa" },
{ label : "New York" , value : "ny" }
]
selectedCity = "ro";
这将设置选定的calue来侮辱罗马。
(*感谢Jeremy Thille,我抄录了我的一部分代码。)