Reputation: 176
I am following PrimeNg Example .and here is a Plunker.How can I make some values pre selected in the drop down.
<p-multiSelect [options]="cities" [(ngModel)]="selectedCities"></p-multiSelect>
Upvotes: 5
Views: 22142
Reputation: 48357
You only need to attach an array of values to selectedCities
variable in order to bind this to the model.
In your case the value property is an object
which contains many properties.
value:{id:1, name: 'New York', cityCode: 'NY'}
The solution is to map
the array items in order to obtain the values you want.
For instance, this will preselect the fist two items
from your dropdown element.
this.selectedCities = this.cities.slice(0,2).map(a => a.value));
If you want to preselect values from a given
array, you should use filter
method.
let arrayOfValues=['NY','IST'];
this.selectedCities = this.cities.filter(a => arrayOfValues.includes(a.value.cityCode)).map(a => a.value));
Upvotes: 11
Reputation: 164
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.
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.
(*thanks to Jeremy Thille. I copied a part of my code from you.)
Upvotes: 0
Reputation: 26360
The selected cities are stored in the selectedCities
array. Since it's a two-way binding, just populate that arry, it will get reflected in the view.
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
Upvotes: 3