网站搜索

angular - 在 ng2-select 中数据绑定失败


我正在尝试使用 ng2-select 将对象数组绑定到下拉菜单。当我尝试使用字符串数组时,它工作得很好。

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

而我的 HTML 如下:

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

我也在我的 module.ts 中导入了 selectModule

答案#1

你的数据格式不正确。

而不是:

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

使用:

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

区别在于value,它表示一个项目的键。这当然是由ng-select模块的开发者定义的。