如何使用 Angular 2 中的 ngModel 在多选中设置默认选定值 [英] How to set default selected values in multiselect with ngModel in Angular 2
问题描述
如何在多选中设置默认选定值.我从数据库中获取 current_options
和 all_options
,我想更新 current_options
并再次发送新的值做数据库.
更新数据库有效,但当我刷新页面时,没有选择任何选项.
current_options = [{id:1, name:'name1'}];#来自数据库all_options = [{id:1, name:'name1'},{id:2, name:'name2'}];#来自数据库
我的模板:
如果你想用 ngModel 创建多个选择和选项并设置默认值和两种方式绑定其工作代码
<br><select [(ngModel)]="res[in]" ><option [ngValue]="option" *ngFor="let option of options.options; let i =index">{{选项}}</选项></选择>{{树脂]}}{{res}}导出类 ExComponent 实现 OnInit {公共资源=[];公共选项数组 = [{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(数据=>{this.res.push(data.options[0]);})}
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>`
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 在多选中设置默认选定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!