首页 > 解决方案 > 如何在angular6中的ng-select中设置默认值?

问题描述

我正在使用angular6 multi-select,它有一个来自角度服务的对象数组中的项目列表,ngOnInit就像这样传递到multi-select

this.sensorTypes = [
  { label : "Power", value : "P"},
  { label : "Current", value : "C"},
  { label : "Voltage", value : "V"}
]

我想在multi-select表单加载时默认设置 2 个值。为此,我绑定ngModelmulti-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>

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

标签: angulartypescriptangular6multi-selectangular-ngselect

解决方案


您应该使用[items]输入绑定而不是[options]

<ng-select 
  [items]="sensorTypes"
  bindLabel="label"                 
  [multiple]="true"
  placeholder="Select"
  [(ngModel)]="selectedAttributes">
</ng-select>

在组件的 module.ts 上,导入NgSelectModule. 如果你还没有导入你的FormsModule,你应该这样做,因为它需要被导入以进行 2 路绑定ngModel才能工作。

import { NgSelectModule } from '@ng-select/ng-select';
import { FormsModule } from '@angular/forms';
.
.
@NgModule({
  imports: [
    FormsModule,
    NgSelectModule,
. 
.
.

推荐阅读