How to get item from `ListView onItemTap($event)` on TypeScript file


#1

How to get index from ListView onItemTap($event) on TypeScript file?

References:

https://docs.nativescript.org/angular/ui/list-view

I’m trying to do that using the code below:

My `productCategories data:

{
  "productCategories": [
    {
      "id": 1,
      "name": "Cafetería"
    },
    {
      "id": 2,
      "name": "Comidas"
    }
  ],

The typings class from ProductCategory object is below:

export class ProductCategory {
  id: number;
  name: string;
}

The product-categories.component.html implementation:

<StackLayout>

  <Label text="Title here" textWrap="true"></Label>

  <ListView
    [items]="productCategories"
    (itemLoading)="onItemLoading(event)"
    (loaded)="onLoaded()"
    (itemTap)="onItemTap($event)"
    class="list-group">

      <ng-template let-item="item" let-odd="odd" let-even="even">

        <StackLayout>

          <Label [text]="item.name" class="list-group-item"></Label>

        </StackLayout>

      </ng-template>

  </ListView>

</StackLayout>

The previous implementation using push():

export class ProductCategoriesComponent {
  public productCategories: Array<ProductCategory> = [];

  constructor(private dataAccess: DataAccessService) { }

  private getProductCategories(productCategoriesList): Array<ProductCategory> {
    const newProductCategoriesList: Array<ProductCategory> = [];

    productCategoriesList.map((item: ProductCategory) => {
      return newProductCategoriesList.push(item);
    });

    return newProductCategoriesList;
  }

or this implementation:

 private getProductCategories(productCategoriesList): Array<ProductCategory> {
    return productCategoriesList.map((item: ProductCategory) => item);
  }

and when implement the onItemTap(args) method:

  public onItemTap(args) {
    const categoryIndex = this.productCategories.indexOf(args.index);

    console.log('=== onItemTap(e) called: ', categoryIndex);
  }

the output:

JS: === onItemTap(e) called:  -1

#2

I always find it a bit messy to use indexes, I’d rather just bind the items itself like this:

    <ng-template let-item="item" let-odd="odd" let-even="even">
      <StackLayout (tap)="onItemTap(item)">
        <Label [text]="item.name" class="list-group-item"></Label>
      </StackLayout>
    </ng-template>
  onItemTap(productCategory: ProductCategory) {
    // now do something with productCategory
  }

#3

Thank’s, @Eddy!!

Seems like using (itemTap) I’ll get index only from simple object.


#4

not sure if this will work for you, but i’m usually using data-attributes instead, mainly for getting item by ID .


#5

Hi @Konrad, I liked this implementation using model.set(...).
I’d like to learn more about it using NativeScript/Angular and a Service to do that as well.