I'm trying to use ListPicker with an object array and my list gets rendered with the label displaying [object Object] for all elements.
I would like to specify which property to use as the "label" for the listpicker.
Unfortunately Nativescript ListPicker only accepts an array of strings and I can't use my Object array as the label will call toString()
I found an alternative solution based on:
buy my app uses page-router-outlet and doesn't use element so I have no way of using the proposed approach above. Given this scenario are there any possible ways of using ListPicker with object arrays or any workaround that doesn't rely on Page element loaded event ?
I'm trying to use ListPicker with an object array and my list gets rendered with the label displaying [object Object] for all elements.
I would like to specify which property to use as the "label" for the listpicker.
Unfortunately Nativescript ListPicker only accepts an array of strings and I can't use my Object array as the label will call toString()
I found an alternative solution based on: https://github./NativeScript/NativeScript/issues/1677
buy my app uses page-router-outlet and doesn't use element so I have no way of using the proposed approach above. Given this scenario are there any possible ways of using ListPicker with object arrays or any workaround that doesn't rely on Page element loaded event ?
Share Improve this question asked Apr 23, 2017 at 2:35 guilheblguilhebl 9,01010 gold badges49 silver badges66 bronze badges2 Answers
Reset to default 7There's an undocumented pull request that makes binding to objects much easier: https://github./NativeScript/NativeScript/pull/6033
Adds new properties to the
ListView
ponent (textField
andvalueField
- should be used with arrays of JSON objects):
textField
- tells the listview which property should be used to display each item.
valueField
- tells the listview, which property should be used to update the selectedValue.
selectedValue
- is the property that will contain theselectedValue
, ifvalueField
is specified, then it will contain the value from that property, otherwise it will contain the whole selected item
Example (Angular):
<ListPicker [items]="printers" textField="name" valueField="id"></ListPicker>
In class:
const printers = [{name: "Printer 1", id: 1}, {name: "Printer 2", id: 2}];
You don't have to use any loaded event at all. Simply override the toString
method and pass the items to the ListPicker:
public countries: any[] = [
{
value: 0,
name: 'Sweden',
toString: () => {
return 'Sweden';
}
},
{
value: 1,
name: 'Denmark',
toString: () => {
return 'Denmark';
}
},
{
value: 2,
name: 'Norway',
toString: () => {
return 'Norway';
}
},
{
value: 3,
name: 'Finland',
toString: () => {
return 'Finland';
}
},
{
value: 4,
name: 'Iceland',
toString: () => {
return 'Iceland';
}
},
];
Pass em to the picker:
<ListPicker [items]="countries"></ListPicker>