如何在angular6的ng-select中设置默认值?

问题描述 投票:4回答:3

我正在使用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>

但是默认情况下,多项选择中未设置值。

angular typescript angular6 multi-select angular-ngselect
3个回答
2
投票
您应该使用[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, . . .


0
投票
默认情况下,多项选择中未设置值

为此,将this.sensorTypes[0]分配给ng-select中的ngOnInit()的ngModel

ngOnInit() { this.selectedAttributes = this.sensorTypes[0] }

这将把第一个属性作为默认属性。

0
投票
如果同时使用bindlabel和bindvalue,则首先查找选定值t的索引e

var index= this.sensorTypes.findIndex(x => x.ID ==something); //this will set value this.selectedAttributes= this.sensorTypes[index].ID;

© www.soinside.com 2019 - 2024. All rights reserved.