Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set by default selected value in angualr2 dropdown using ng-select?

I have used angular2 drop-down for multiple value using follwing code:

 <ng-select [options]="dropDownSKUNumber" #SKUNumberDrp multiple="true" placeholder="Select SKU Number"  [allowClear]="true"></ng-select>

This code is working properly for me at the time of save multiple value. Then but in view mode, I want that values by default in selected mode in dropdown, But i can't be able to do this.

How to solve it? using above code.

like image 530
Mansi Kalola Avatar asked Dec 02 '16 05:12

Mansi Kalola


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.

How do I set the default selected value?

The default value of the select element can be set by using the 'selected' attribute on the required option. This is a boolean attribute. The option that is having the 'selected' attribute will be displayed by default on the dropdown list.

What is the default value for appendTo?

The default value for appendTo is the ng-select component itself. It will render the select panel as a child of that component. By passing a selector for appendTo , you are telling the component that it should find that element in the DOM and attach it as a child there.


Video Answer


2 Answers

Since you are using options, you must be using this ng2-select. In this case, you should bind it to an ngModel and then update that value on init of your script:

I.e. HTML

<ng-select
    [multiple]="true"
    [options]="myOptions"
    [(ngModel)]="mySelectValue">
</ng-select>

TS

export class App implements OnInit {

    myOptions: Array<any>;
    mySelectValue: Array<string>; // Array of strings for multi select, string for single select.

    ngOnInit() {
        this.myOptions = [
            {value: 'a', label: 'Alpha'},
            {value: 'b', label: 'Beta'},
            {value: 'c', label: 'Gamma'},
        ];
        this.mySelectValue = ['b', 'c'];
    }
}
like image 151
Ajk_P Avatar answered Nov 15 '22 03:11

Ajk_P


According to angular2 select you can use ngModel to set initial value :

you can use options as array and ngModle for selected value in your component as below :

//Component 
public dropDownSKUNumber : any[] = [
  { value: 1, label : 1 },
  { value: 2, label : 2 },
  { value: 3, label : 3 }
];
public selectedValue: string[] = [ '2', '3' ];

//HTML
<ng-select [options]="dropDownSKUNumber" #SKUNumberDrp multiple="true" placeholder="Select SKU Number" [(ngModel)]="selectedValue" [allowClear]="true"></ng-select>
like image 22
ranakrunal9 Avatar answered Nov 15 '22 03:11

ranakrunal9