Not able to get element's native view in NativeScript

流过昼夜 提交于 2020-01-05 06:28:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!