问题
I am trying to change the width of some Switch elements in NativeScript with Angular because they are too small in my opinion. I have found that there is no way to do this through NativeScript's CSS subset so that means I have to make the change to the native object itself.
To do this I have added a template reference variable to each one of the switches in my template like this:
<Switch #switch checked="false"></Switch>
Then in my class I try to access their android
and nativeView
properties like this:
@Component({
selector: "Settings",
moduleId: module.id,
templateUrl: "./settings.component.html"
})
export class SettingsComponent implements AfterViewInit {
@ViewChildren("switch") switches: QueryList<ElementRef>;
constructor(public calc: CalculationService) {
}
ngAfterViewInit() {
console.log("afterViewInit switches: ", this.switches.length);
if(isAndroid) {
this.switches.forEach(
(item) => {
const nelem = item.nativeElement;
console.log(nelem.android);
console.log(nelem.nativeView);
}
);
}
}
}
But the two console.log
statements where I'm accessing them just print undefined
. How do I get the native view of the switches?
回答1:
The Switch
is a NativeScript's component and not Angular. The thing is that the Angular abstraction is on top of the mobile one so some native mobile elements might not be loaded when the Angular lifecycles are triggered.
To resolve that make sure you are using NativeScript's lifecycles to gett reference to nativeScript's mobile components.
You can achieve that in the following way:
import { Component, ViewChildren, QueryList, ElementRef} from "@angular/core";
import { isAndroid } from "platform";
import { Page } from "ui/page";
@Component({
selector: "ns-items",
moduleId: module.id,
templateUrl: "./items.component.html",
})
export class ItemsComponent {
@ViewChildren("switch") switches: QueryList<ElementRef>;
constructor(private _page: Page) {
this._page.on("loaded", () => {
console.log("afterViewInit switches: ", this.switches.length);
if (isAndroid) {
this.switches.forEach(
(item) => {
const nelem = item.nativeElement;
console.log(nelem.android);
console.log(nelem.nativeView);
}
);
}
})
}
}
来源:https://stackoverflow.com/questions/51201181/not-able-to-get-elements-native-view-in-nativescript