在带有Angular的NativeScript中,如何获取接口元素的ID? [英] In NativeScript with Angular, how can I get an interface element the id?
问题描述
我试图避免在NativeScript应用程序中发生意外行为.
I'm trying to avoid unexpected behavior in a NativeScript application.
当我进入具有搜索字段(SearchBar)的任何屏幕时,系统会自动将焦点放在搜索字段上.
When I walk into any screen that has a search field (SearchBar) system puts the focus on the search field automatically.
然后,我得到了一位朋友的帮助,后者为我提供了解决此问题的功能.但是我现在面临的问题是我无法获取接口元素.我有以下代码:
Then I got help with a friend who gave me a function to solve this problem. But the problem I'm facing right now is that I can not get the interface element. I have the following code:
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>
我的目标是获取搜索字段的自动焦点,但无法获取界面元素.
My goal is to get the auto focus of the search field, but I can not get the interface element.
推荐答案
在此之上扩展Nikolay的答案,以使用@ViewChild
将#foo添加到您的堆栈布局中,使其看起来像:
to expand on Nikolay's answer above this to use @ViewChild
add #foo to your stack layout so it looks like:
<StackLayout #foo ....
然后:
@ViewChild('foo') stackLayout: ElementRef;
ngAfterViewInit() {
let yourStackLayoutInstance = this.stackLayout.nativeElement;
}
它不会通过ID来获取元素,但这是ng2与元素进行交互的方式,它可以使您的代码更松散地耦合到DOM.
it won't get the element by ID but this is the more ng2 way of interacting with elements and keeps your code more loosely coupled to the DOM.
这篇关于在带有Angular的NativeScript中,如何获取接口元素的ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!