问题
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>`
回答1:
If you want create multiple select and option with ngModel and set default value and two way bind its working code
<div *ngFor="let options of optionsArray; let in = index">
<br>
<select [(ngModel)]="res[in]" >
<option [ngValue]="option" *ngFor="let option of options.options; let i =index">
{{option}}
</option>
</select>
{{res[in]}}
</div>
{{res}}
export class ExComponent implements OnInit {
public res=[];
public optionsArray = [
{id: 1, text: 'Sentence 1', options:['kapil','vinay']},
{id: 2, text: 'Sentence 2', options:['mukesh','anil']},
{id: 3, text: 'Sentence 3', options:['viky','kd']},
{id: 4, text: 'Sentence 4', options:['alok','gorva']},
]
ngOnInit()
{
this.optionsArray.forEach(data=>{
this.res.push(data.options[0]);
})
}
回答2:
If you will pass the values as an id array to ngModel
let idArrary = ["1"];
<select multiple name="type" [(ngModel)]="idArrary">
<option *ngFor="let option of all_options" [ngValue] = "option">
{{option.name}}
</option>
</select>
`
回答3:
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
回答4:
current_options = [all_options[0]]
To initialize the default value of your input.
Current_options need to be initialize with an array containing the same objects present in all_options.
I forked the Plunker from another answer to illustrate it.
Keep in mind that :
{id:1, name:'name1'} !== {id:1, name:'name1'}
Edit:
Assuming current_options is already containing some value you are receiving from your server:
current_options = current_options.map((current_option) => {
return all_options.find((all_option) => current_option.id === all_option.id);
})
Or probably more performant:
for (let i in all_options) {
for (let j in current_options) {
if (all_options[i].id === current_options[j].id ) {
current_options[j] = all_options[i];
}
}
}
Edit: According to angular documentation you can use a compare with function to specify how to assume two objects are equal.
<select multiple [compareWith]="compareFn" ...>
</select>
compareFn(c1: Category, c2: Category): boolean {
return c1 && c2 ? c1.id === c2.id : c1 === c2;
}
来源:https://stackoverflow.com/questions/47692212/how-to-set-default-selected-values-in-multiselect-with-ngmodel-in-angular-2