angulartypescriptangular6multi-selectangular-ngselect

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


Solution

  • 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,
    . 
    .
    .