Search code examples
javascriptnativescriptangular2-nativescript

Nativescript Use LIstPicker with JS object


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.com/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 ?


Solution

  • 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>