5

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>
zgue
  • 3,793
  • 9
  • 34
  • 39
Mukul Sharma
  • 176
  • 2
  • 5
  • 19
  • You might have a look at **[How to set default value for PrimeNG p-dropdown](https://stackoverflow.com/questions/49623774/how-to-set-default-value-for-primeng-p-dropdown/52290047#52290047)**. – Murat Yıldız Sep 12 '18 at 07:49

3 Answers3

11

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));
Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128
  • In PrimeNG Dropdown p-dropdown is it possible to pass value as string rather than object – ShaMoh Apr 30 '18 at 07:13
  • 1
    For default selection, selected items is not showing in the input. If we handle selectedCities from .ts dynamically then we are not able to see how many items are selected in the input. It simply displays choose placeholder. How to resolve this? – pjay Nov 08 '19 at 07:56
3

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
Jeremy Thille
  • 26,047
  • 12
  • 43
  • 63
0

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.)