Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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>`
like image 987
pelcomppl Avatar asked Dec 07 '17 09:12

pelcomppl


1 Answers

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

like image 181
Aravind Avatar answered Sep 22 '22 15:09

Aravind