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.
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.
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 .
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With