如何在Angular 2中使用ngModel在multiselect中设置默认选定值

时间:2017-12-07 09:54:16

标签: angular angular-ngmodel angular2-ngmodel ngmodel

如何在multiselect中设置默认选定值。我从数据库中获取current_optionsall_options,我想更新current_options并再次发送新值数据库。

更新数据库有效,但当我刷新页面时,没有选择任何选项。

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>`

4 个答案:

答案 0 :(得分:2)

您应该使用一系列选定的项目

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

我选择的项目如下

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

<强> LIVE DEMO

答案 1 :(得分:2)

current_options = [all_options[0]] 初始化输入的默认值。

Current_options需要使用包含all_options中存在的相同对象的数组进行初始化。

我从另一个答案中分出Plunker来说明它。

请记住:

{id:1, name:'name1'} !== {id:1, name:'name1'}

修改

假设current_options已包含您从服务器收到的某些值:

current_options = current_options.map((current_option) => {
   return all_options.find((all_option) => current_option.id === all_option.id);
})

或者可能性能更高:

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]; 
      } 
   } 
}

修改 根据angular documentation,您可以使用与函数的比较来指定如何假设两个对象相等。

<select multiple [compareWith]="compareFn" ...>
</select>

compareFn(c1: Category, c2: Category): boolean {
  return c1 && c2 ? c1.id === c2.id : c1 === c2;
}

答案 2 :(得分:2)

如果您将值作为id数组传递给ngModel

let idArrary = ["1"];

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

`

答案 3 :(得分:0)

如果要使用ngModel创建多个select和option并设置默认值和两种方式绑定其工作代码

<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]);
})
}