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

pel*_*ppl 5 angular-ngmodel angular2-ngmodel ngmodel angular

如何在多选中设置默认选定值。我从数据库中获取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
Run Code Online (Sandbox Code Playgroud)

我的模板:

<select multiple name="type" [(ngModel)]="current_options">
    <option  *ngFor="let option of all_options" [ngValue] = "option">
        {{option.name}}
    </option>
</select>`
Run Code Online (Sandbox Code Playgroud)

Ara*_*ind 6

您应该使用一组选定的项目

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

我选择的项目如下

selectedElement:any= [
                {id:1,Name:'abc'},
                {id:2,Name:'abdfsdgsc'}];
Run Code Online (Sandbox Code Playgroud)

现场演示


Ans*_*hul 5

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

let idArrary = ["1"];

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

`


小智 1

如果您想使用 ngModel 创建多个选择和选项并设置默认值和两种方式绑定其工作代码

<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]);
})
}
Run Code Online (Sandbox Code Playgroud)