Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 1000
Fahad Subzwari Avatar asked Feb 21 '19 06:02

Fahad Subzwari


People also ask

How do I set default selected value in ng options?

In my opinion the correct way to set a default value is to simply pre-fill your ng-model property with the value selected from your ng-options , angular does the rest. Essentially when you define the $scope property your select will bind to assign it the default value from your data array.

What is the use of NG select?

AngularJS ng-selected Directive The ng-selected directive sets the selected attribute of an <option> element in a <select> list. The option will be selected if the expression inside the ng-selected attribute returns true. The ng-selected directive is necessary to be able to shift the value between true and false .


1 Answers

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

var index= this.sensorTypes.findIndex(x => x.ID ==something); 
//this will set value
this.selectedAttributes= this.sensorTypes[index].ID;
like image 60
Manan bhavsar Avatar answered Sep 28 '22 11:09

Manan bhavsar