Skip to content

Issues with ngAfterViewInit #2380

@jiwonyune

Description

@jiwonyune

I posted a question on StackOverflow (http://stackoverflow.com/questions/38084180/nativescript-issue-with-loading-view). The issue is basically that I cannot get or set properties of UI components when the page is loaded. I already tried to use ngAfterViewInit() or (loaded) from the template, but they don't seem to work at all.

This is my template page_2.html:

<StackLayout>
    <Label text="to page 1" class="button_label" (tap)="to_page1()"></Label>
    <Label #label_in_2 text="second label" class="test_label" (loaded)="whatisthewidth(label_in_2)"></Label>
</StackLayout>

This is the style file page_2-common.css:

Label.test_label {
    background-color: yellow;

    width: 75%;
    height: 20%;
}

And this is page_2.component.ts:

import {Component, ViewChild, ElementRef, OnInit} from "@angular/core";
import {Router} from "@angular/router-deprecated";

import {Page} from "ui/page";

import {Label} from "ui/label";

@Component({
    selector: "page2",
    templateUrl: "pages/page_2/page_2.html",
    styleUrls: ["pages/page_2/page_2-common.css", "pages/page_2/page_2.css"]
})

export class Page2 implements OnInit {

    @ViewChild("label_in_2") label_in_2: ElementRef;

    constructor(private _router: Router, private page: Page) {}

    ngOnInit() {

    }

    ngAfterViewInit() { // trial 1
        let label = <Label>this.label_in_2.nativeElement;

        console.log("width of the label 2 in ngAfterViewInit: " + label.getActualSize().width); // give me 0
    }

    whatisthewidth(testLabel) {

        console.log("width of the label 2 in whatisthewidth: " + testLabel.getActualSize().width); // give me 0
    }

    to_page1() {
        let label = <Label>this.label_in_2.nativeElement;

        console.log("width of the label 2: " + label.getActualSize().width); // give me the correct value

        console.log("to page 1");
        this._router.navigate(["Page1"]);
    }

}

How can I get or set properties of UI components from .ts files properly and correctly?

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions