How to set default selected values in multiselect with ngModel in Angular 2

pelcomppl picture pelcomppl · Dec 7, 2017 · Viewed 14.7k times · Source

How to set default selected values in multiselect. I get current_options and all_options from database and I want to update current_options and send new values do database again.

Updating database works but when I refresh page none of options are selected.

current_options = [{id:1, name:'name1'}];                    #from database
all_options = [{id:1, name:'name1'},{id:2, name:'name2'}];   #from database

My template:

<select multiple name="type" [(ngModel)]="current_options">
    <option  *ngFor="let option of all_options" [ngValue] = "option">
        {{option.name}}
    </option>
</select>`

Answer

Aravind picture Aravind · Dec 7, 2017

You should be using an array of selected items

<select [(ngModel)]="selectedElement" multiple>
     <option *ngFor="let type of types" [ngValue]="type"> {{type.Name}}</option>
</select>

My selected item will be as below

selectedElement:any= [
                {id:1,Name:'abc'},
                {id:2,Name:'abdfsdgsc'}];

LIVE DEMO