In NativeScript with Angular2 get element value

北战南征 提交于 2019-12-20 05:39:16

问题


I have a list, and I want to get the value of the list item.

The view is as follows

<ListView  [items]="myItems" (itemTap)="onItemTap($event)">
<template let-item="item" let-i="index" let-odd="odd" let-even="even">
    <StackLayout [class.odd]="odd" [class.even]="even">
        <Label #myFoo id="grocery-list" [text]='"Value is: " + i'></Label>
    </StackLayout>
</template>

In typescript I have the following

import { Component,ViewChild,ElementRef } from "@angular/core";
import {topmost} from "ui/frame";
import {ListView} from "ui/list-view";
 export class AppComponent {

 @ViewChild("myFoo") myFooRef: ElementRef;

    public myItems = [];
    constructor() {
          this.myItems.push("1");
          this.myItems.push("2");
          this.myItems.push("3");

   }

    onItemTap(event){

    }
}

I can do the following to get the value

    onItemTap(event){
    let itemValue = this.myItems[event.index];
     console.log(itemValue);     
    }

This will get the value in the array. But this will return the value in the array only.

As you can see in the view I have the string Value is appended to the value.

So how can I access the text property of the label which is tapped on.


回答1:


You can access the view of your item template via args.view. From that point, I assume that you will have different text in your list-items so it is important to create unique IDs for each Label via binding(using the Angular index). So you can do the following:

<ListView  [items]="myItems" (itemTap)="onItemTap($event)">
    <template let-item="item" let-i="index" let-odd="odd" let-even="even">
        <StackLayout [class.odd]="odd" [class.even]="even">
            <Label [id]="'lbl' + i" [text]='"Value is: " + i'></Label>
        </StackLayout>
    </template>
</ListView>

and then in your onItemTap

public onItemTap(args: ItemEventData) {
    console.log("Item Tapped at cell index: " + args.index);
    console.log(args.object); // prints something like ListView(137)
    console.log(args.view); // prints something like StackLayout(265)

    var lbl = <Label>args.view.getViewById("lbl" + args.index);

    console.log(lbl.text); // prints the actual text of the tapped label
}


来源:https://stackoverflow.com/questions/41809113/in-nativescript-with-angular2-get-element-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!