2

I am trying to bind array of object to dropdown using ng2-select.It works fine when I tried using array of string

private category: Array<object> = [{ "value": 1, "text": "Table" }, { "value": 2, "text": "Chair" }, { "value": 3, "text": "Light"}]

and my html as follow:

 <ng-select [items]="category" [allowClear]="true"
                                       placeholder="No country selected">
                            </ng-select>

I have also Imported selectModule in my module.ts

user19041992
  • 133
  • 1
  • 5
  • 18

1 Answers1

4

Format of your data is not correct.

Instead of:

private category: Array<object> = [
    { "value": 1, "text": "Table" },
    { "value": 2, "text": "Chair" },
    { "value": 3, "text": "Light" }
]

Use:

private category: Array<object> = [
    { "id": 1, "text": "Table" },
    { "id": 2, "text": "Chair" },
    { "id": 3, "text": "Light" }
]

The difference is in value which represents key of one item. This i ofcourse defined by ng-select module developer.

Mario Petrovic
  • 7,500
  • 14
  • 42
  • 62
  • but what if data is coming from web api? Is it compulsory to convert data in {id:" ",text:" " } format – user19041992 Apr 21 '17 at 13:36
  • Yes, you need to do that. Since there is no way you can define what is the key and what is the value in your object, it is just not exposed by developer of ng-select. But this is not uncommon in most dropdown modules. – Mario Petrovic Apr 21 '17 at 13:38