我正在使用angular6 multi-select
,其中具有从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"}
]
在我的component.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, . . .
默认情况下,多项选择中未设置值
为此,将this.sensorTypes[0]
分配给ng-select
中的ngOnInit()
的ngModel
ngOnInit() {
this.selectedAttributes = this.sensorTypes[0]
}
这将把第一个属性作为默认属性。
var index= this.sensorTypes.findIndex(x => x.ID ==something);
//this will set value
this.selectedAttributes= this.sensorTypes[index].ID;