我正在使用 angular6multi-select
它有一个项目列表,这些项目来自 angular 服务的对象数组ngOnInit
像这样传递到multi-select
:
this.sensorTypes = [
{ label : "Power", value : "P"},
{ label : "Current", value : "C"},
{ label : "Voltage", value : "V"}
]
我想在加载表单时multi-select
默认设置 2 个值。为此,我将ngModel
绑定multi-select
并在该变量中设置ngOnInit
这样的值
this.selectedAttributes = [
{label : "Current", value : "C"},
{label : "Voltage", value : "V"}
]
在我的组件中.html我正在创建这样的multi-select
:
<div class="form-group row">
<div class="col-sm-10">
<ng-select
[ngClass]="'ng-select'"
[(ngModel)]="selectedAttributes"
[ngModelOptions]="{standalone: true}"
[options]="sensorTypes"
[multiple]="true">
</ng-select>
</div>
</div>
但默认情况下不会在多选中设置值。
您应该使用[items]
输入绑定而不是[options]
<ng-select
[items]="sensorTypes"
bindLabel="label"
[multiple]="true"
placeholder="Select"
[(ngModel)]="selectedAttributes">
</ng-select>
然后在组件的 module.ts 上,导入NgSelectModule
.如果您还没有导入FormsModule
,则应这样做,因为它需要导入才能与ngModel
进行 2 路绑定才能工作。
import { NgSelectModule } from '@ng-select/ng-select';
import { FormsModule } from '@angular/forms';
.
.
@NgModule({
imports: [
FormsModule,
NgSelectModule,
.
.
.
如果您同时使用绑定标签和绑定值,那么首先要找到所选值 T 的索引 e
var index= this.sensorTypes.findIndex(x => x.ID ==something);
//this will set value
this.selectedAttributes= this.sensorTypes[index].ID;
多选中默认不设置
为此,this.sensorTypes[0]
分配给 ngng-select
的 ngModel 在ngOnInit()
ngOnInit() {
this.selectedAttributes = this.sensorTypes[0]
}
这将获取第一个属性作为默认属性。
有两种不同的 ng-select 模块:
@ng-select/ng-select
ng-select
两个指令标签是相同的,并且 ng-select 中使用的 [选项] 和@ng-select/ng-select
中使用的 [items]
ng-select 文档 https://basvandenberg.github.io/ng-select/#/documentation
使用其中任何一个都是您的选择