簡體   English   中英

在使用Angular的NativeScript中,如何獲取id的接口元素?

[英]In NativeScript with Angular, how can I get an interface element the id?

我試圖避免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>

我的目標是獲得搜索字段的自動焦點,但我無法獲得界面元素。

為了擴展Nikolay上面的回答,使用@ViewChild將#foo添加到你的堆棧布局中,它看起來像:

<StackLayout #foo ....

然后:

@ViewChild('foo') stackLayout: ElementRef;

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

它不會通過ID獲取元素,但這是與元素交互的更多ng2方式,並使您的代碼更加松散地耦合到DOM。

要在項目中獲取元素,您應該使用@ViewChild裝飾器,它將幫助您創建指向SearchBar新屬性。 關於這一點,您可以在此處查看我的項目,還可以查看本文: 使用NativeScript和Angular 2構建應用程序

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM