简体   繁体   中英

How to set default values in ng-select in angular6?

I am using angular6 multi-select which have a list of items coming in an array of objects from angular service on ngOnInit like this which is passing into multi-select :

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

I want to set 2 values by default in multi-select when form will load. For this i am binding ngModel on multi-select and in that variable i am setting values on ngOnInit like this

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

In my component.html i am creating multi-select like this :

<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>

But values are not setting by default in multi-select.

You should use the [items] input binding instead of [options]

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

And on your component's module.ts, import the NgSelectModule . And if you haven't import your FormsModule , you should do so, as it needs to be imported for 2 way binding with ngModel to work.

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

if you are using both bindlabel and bindvalue so fist find index of selected value te

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

values are not setting by default in multi-select

for this assign this.sensorTypes[0] to ngModel of your ng-select in ngOnInit()

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

this will get the first attribute as the default one.

There are two different ng-select modules:

  • @ng-select/ng-select
  • ng-select

both directive tags are same and [options] used in ng-select and [items] used in @ng-select/ng-select

ng-select documentation https://basvandenberg.github.io/ng-select/#/documentation

Its all your choice to use any of one

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM