如何修复在 NativeScript Angular 中未定义的 @ViewChild ElementRef?

bgr*_*-ch 6 scrollview nativescript viewchild nativescript-angular elementref

我正在使用 NativeScript (CLI v5.2.0) Angular (v7.2.3) 开发移动应用程序,并且我的 @ViewChild ElementRef 未定义。

我在“@angular/core”的导入中检查了 ViewChild 和 ElementRef 的存在,重命名了我的 @ViewChild 变量,将范围从 public 更改为 private,在 ngAfterViewInit 中移动了 console.log() (参见:https://github .com/NativeScript/nativescript-angular/issues/188#issuecomment-212815619)并使用“tns debug android --clean --bundle”重建我的项目。

组件名称.component.ts :

@ViewChild("test") private _scrollView: ElementRef;

constructor(page: Page) {

    page.actionBarHidden = true;

}

ngAfterViewInit() {

    console.log("ScrollView element:", this._scrollView.nativeElement);

}

...
Run Code Online (Sandbox Code Playgroud)

组件名称.component.html :

<GridLayout columns="*" rows="*, auto">

    <ScrollView (swipe)="onSwipe($event)" col="0" row="0" #test>
        <StackLayout>

...
Run Code Online (Sandbox Code Playgroud)

如果我将 #test 放在开头,就在 ScrollView 元素之后,我有未定义的“this._scollView”变量。

如果我把 #test 放在最后,就像上面的例子一样,一切正常,我在 console.log(this._scrollView.nativeElement) 中显示我的元素!

一个错误?

小智 2

以前的代码:

import { ElementRef } from "@angular/core";

@ViewChild("myElement") myElement: ElementRef;
Run Code Online (Sandbox Code Playgroud)

迁移后的代码:

import { ElementRef } from "@angular/core";

@ViewChild("myElement", { static: false }) myElement: ElementRef;

{static: false} means nfAfterInit,
{static: true} mean ngInit
Run Code Online (Sandbox Code Playgroud)

它对我有用。