Matt Donovan
Matt Donovan

Reputation: 21

Adding inline styles programmatically in NativeScript

I'm teaching myself the basics for NativeScript.

This is my main-page.xml:

<Page xmlns="http://www.nativescript.org/tns.xsd" loaded="pageLoaded">
  <GridLayout id="grid">

  </GridLayout>
</Page>

This is the JS code:

var view = require("ui/core/view");
var layout = require("ui/layouts/grid-layout");

function pageLoaded(args) {
    var page = args.object;
    var gr = view.getViewById(page, "grid");
    if (gr) {
        for (var i = 0; i < 10; i++) {
            gr.addColumn(new layout.ItemSpec(1, layout.GridUnitType.star));
            var g = new layout.GridLayout();
            g.style = "{ background-color: red; }";
            layout.GridLayout.setColumn(g, i);
            gr.addChild(g);
        }
    }
}

exports.pageLoaded = pageLoaded;

How does one programmatically set the style for a grid created in code-behind? When I run the code, I don't see anything in red. Ideally, I'd like to be able to add styles without creating a css class or selecting css by id. Is this possible i.e. adding in-line styles?

EDIT: Fixed the typo in "{ backgroud-color: red; }";

Upvotes: 2

Views: 2729

Answers (1)

Alexander Vakrilov
Alexander Vakrilov

Reputation: 1131

You can set the background as a property of the style object:

g.style.backgroundColor = new colorModule.Color("Red");

Check the "JavaScript property" column here if you need to access other properties for the style object.

Upvotes: 3

Related Questions