首页 文章

无法在NativeScript中获取元素的本机视图

提问于
浏览
1

我试图用Angular改变NativeScript中一些Switch元素的宽度,因为在我看来它们太小了 . 我发现通过NativeScript的CSS子集无法做到这一点,这意味着我必须对原生对象本身进行更改 .

为此,我为模板中的每个开关添加了一个模板引用变量,如下所示:

<Switch #switch checked="false"></Switch>

然后在我的课上我尝试访问他们的 androidnativeView 属性,如下所示:

@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);
        }
      );
    }
  }
}

但是我正在访问它们的两个 console.log 语句只打印 undefined . 如何获取交换机的本机视图?

1 回答

  • 1

    Switch 是NativeScript的组件,而不是Angular . 问题是Angular抽象位于移动抽象之上,因此在触发Angular生命周期时可能无法加载某些本机移动元素 .

    要解决此问题,请确保使用NativeScript的生命周期来引用nativeScript的移动组件 .

    您可以通过以下方式实现此目的:

    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);
                        }
                    );
                }
            })
        }
    }
    

相关问题