本文介绍了在带有 Angular2 的 NativeScript 中获取元素值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表,我想获取列表项的值.

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

视图如下

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

正如您在视图中看到的,我将字符串 Value is 附加到值.

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

那么我如何访问被点击的标签的 text 属性.

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

推荐答案

您可以通过 args.view 访问您的项目模板的视图.从那时起,我假设您的列表项中会有不同的文本,因此通过绑定(使用 Angular 索引)为每个标签创建唯一 ID 非常重要.因此,您可以执行以下操作:

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>

然后在您的 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
}

这篇关于在带有 Angular2 的 NativeScript 中获取元素值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 04:43