How to fix @ViewChild ElementRef undefined in NativeScript Angular?
Asked Answered
A

1

7

I am developing a mobile application with NativeScript (CLI v5.2.0) Angular (v7.2.3) and I have my @ViewChild ElementRef that was undefined.

I checked the presence of ViewChild and ElementRef in the import of "@angular/core", renamed my @ViewChild variable, changed the scope from public to private, moved the console.log() in ngAfterViewInit (see: https://github.com/NativeScript/nativescript-angular/issues/188#issuecomment-212815619) and rebuilt my project with "tns debug android --clean --bundle".

component-name.component.ts :

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

constructor(page: Page) {

    page.actionBarHidden = true;

}

ngAfterViewInit() {

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

}

...

component-name.component.html :

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

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

...

If I put #test at the beginning, just after the ScrollView element, I have "this._scollView" variable that is undefined.

If I put #test at the end, like the example above, everything works and I show my element in the console.log(this._scrollView.nativeElement)!

A bug ?

Air answered 15/2, 2019 at 13:21 Comment(2)
I have a habit of placing id right after the tag name, it always works for me. May be can you write a Playground sample to demonstrate the issue?Aksel
Good afternoon @Aksel ! Thanks for your answer. Unfortunately, I do not know how to use the NativeScript Playground website. But everything is functional on my side as explained above :) Have a nice day.Air
I
2

Previous code:

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

@ViewChild("myElement") myElement: ElementRef;

Migrated code:

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

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

{static: false} means nfAfterInit,
{static: true} mean ngInit

its works for me.

Ithunn answered 15/2, 2021 at 8:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.