javascript 如何在 angular 2 和 ngprime 中设置下拉多选的默认值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46425361/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to set default value for drop-down multiselect in angular 2 and ngprime
提问by Mukul Sharma
I am following PrimeNg Example .and here is a Plunker.How can I make some values pre selected in the drop down.
我正在关注PrimeNg 示例。这里是一个Plunker。如何在下拉列表中预先选择一些值。
<p-multiSelect [options]="cities" [(ngModel)]="selectedCities"></p-multiSelect>
回答by Mihai Alexandru-Ionut
You only need to attach an arrayof values to selectedCitiesvariable in order to bind this to the model.
您只需要将一组值附加到selectedCities变量即可将其绑定到模型。
In your case the valueproperty is an objectwhich contains many properties.
在您的情况下,value属性是object包含许多属性的an 。
value:{id:1, name: 'New York', cityCode: 'NY'}
The solution is to mapthe array items in order to obtain the values you want.
解决方案是map通过数组项来获取您想要的值。
For instance, this will preselect the fist twoitemsfrom your dropdownelement.
例如,这将从您的下拉元素中预选前两个。items
this.selectedCities = this.cities.slice(0,2).map(a => a.value));
If you want to preselect values from a givenarray, you should use filtermethod.
如果你想从given数组中预选值,你应该使用filtermethod。
let arrayOfValues=['NY','IST'];
this.selectedCities = this.cities.filter(a => arrayOfValues.includes(a.value.cityCode)).map(a => a.value));
回答by Jeremy Thille
The selected cities are stored in the selectedCitiesarray. Since it's a two-way binding, just populate that arry, it will get reflected in the view.
所选城市存储在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
回答by Ashkan R. Nejad
There is a good way you can define value for each of your options. Then define the variable selectedCities to the value you want as defult. It will make the angular to choose that vale option on initialization.
有一个很好的方法可以为每个选项定义值。然后将变量 selectedCities 定义为您想要的默认值。它将使角度在初始化时选择该 vale 选项。
let Cities: SelectItem[] = [
{ label : "Rome" , value : "ro" },
{ label : "London" , value : "lo" },
{ label : "Paris" , value : "pa" },
{ label : "New York" , value : "ny" }
]
selectedCity = "ro";
this will set the Selected calue to defult Rome.
这将设置 Selected calue to defult Rome。
(*thanks to Jeremy Thille. I copied a part of my code from you.)
(*感谢 Jeremy Thille。我从你那里复制了我的一部分代码。)

