Search code examples
nativescript

Getting a page view element from a model class


I've got a model class and would like to get access to a ui element.

frameModule.topmost().getViewById("id") or

frameModule.topmost().page.getViewById("id")

don't work.


Solution

  • As I understand what you need, I hope this solution would help.

    In XML, assuming that you have UI Element with an ID. You will get it in the controller. For example:

    In page.xml:

    <Label id="test"/>
    

    In the binding object class in page-view-model.js, create a property that has type of label:

    var labelModule = require("ui/label");
    var Label = labelModule.Label;
    
    class Someclass extends Observable {
        public label: Label;
    }
    

    In page.js:

    function pageLoaded(args) {
        var page = args.object;
        var myLabel = page.getViewById("test");
        var context = new Someclass();
        page.bindingContext = context;
        context.label = myLabel;
    }