【问题标题】:In NativeScript with Angular, how can I get an interface element the id?在带有 Angular 的 NativeScript 中,如何获取 id 的界面元素?
【发布时间】:2016-10-19 10:38:52
【问题描述】:

我正在尝试避免 NativeScript 应用程序中出现意外行为。

当我走进任何具有搜索栏 (SearchBar) 的屏幕时,系统会自动将焦点放在搜索栏上。

然后我得到了一个朋友的帮助,他给了我一个解决这个问题的函数。但是我现在面临的问题是我无法获取界面元素。我有以下代码:

import {Component} from "@angular/core";
import {Page} from "ui/page";
import frame = require("ui/frame");

@Component({
    selector: "clientes",
    templateUrl: "pages/clientes/clientes.html",
    styleUrls: ["pages/clientes/clientes.common.css",
    "pages/clientes/clientes.css"]
})

export class ClientesPage {

    page;

    constructor(private _router: Router) {
        this.page = <Page>frame.topmost().currentPage;
        this.removeSearchFocus();
    }

    removeSearchFocus() {
        var parent = this.page.getViewById('box-lista');
        var searchBar = this.page.getViewById('barra-busca');

        console.log(JSON.stringify(parent)); // UNDEFINED
        console.log(JSON.stringify(searchBar)); // UNDEFINED

        if (parent.android) {
            parent.android.setFocusableInTouchMode(true);
            parent.android.setFocusable(true);
            searchBar.android.clearFocus();
        }

    }
}

然后我有了模板:

<Page.actionBar>
    <ActionBar title="Clientes"></ActionBar>
</Page.actionBar>

<StackLayout orientation="vertical" id="box-lista">
    <SearchBar hint="Buscar" cssClass="mh mv" id="barra-busca"></SearchBar>
</StackLayout>

我的目标是获得搜索字段的自动焦点,但我无法获得界面元素。

【问题讨论】:

  • 请忽略构造函数中的“private_router:Router”。

标签: javascript android typescript nativescript nativescript-angular


【解决方案1】:

扩展 Nikolay 在上面的回答以使用 @ViewChild 将 #foo 添加到您的堆栈布局中,使其看起来像:

&lt;StackLayout #foo ....

然后:

@ViewChild('foo') stackLayout: ElementRef;

ngAfterViewInit() {
    let yourStackLayoutInstance = this.stackLayout.nativeElement;
} 

它不会通过 ID 获取元素,但这是与元素交互的更 ng2 方式,并使您的代码更松散地耦合到 DOM。

【讨论】:

【解决方案2】:

要在您的项目中获取元素,您应该使用@ViewChild 装饰器,这将帮助您创建指向SearchBar 的新属性。关于这一点,您可以查看我的项目here,也可以查看这篇文章:Building Apps with NativeScript and Angular 2

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-05
    相关资源
    最近更新 更多