Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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>
like image 843
Mukul Sharma Avatar asked Sep 26 '17 11:09

Mukul Sharma


2 Answers

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));
like image 160
Mihai Alexandru-Ionut Avatar answered Oct 18 '22 03:10

Mihai Alexandru-Ionut


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
like image 28
Jeremy Thille Avatar answered Oct 18 '22 04:10

Jeremy Thille