如何在Angular 2中使用ngModel在multiselect中设置默认选择的值 [英] How to set default selected values in multiselect with ngModel in Angular 2
本文介绍了如何在Angular 2中使用ngModel在multiselect中设置默认选择的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在多重选择中设置默认选择的值。我从数据库中获得了 current_options
和 all_options
,我想更新 current_options
并发送新值再次执行数据库操作。
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
我的模板:
<select multiple name="type" [(ngModel)]="current_options">
<option *ngFor="let option of all_options" [ngValue] = "option">
{{option.name}}
</option>
</select>`
推荐答案
如果您要使用ngModel创建多个select和option并设置默认值,并通过两种方式绑定其工作代码
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]);
})
}
这篇关于如何在Angular 2中使用ngModel在multiselect中设置默认选择的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文