0

I just started using Nativescript. I have a button declared in the XML calling (id="mainButton" class="btn") an external css file. Everything works fine (button originally renders in blue). However, I need to change its color to red, via code.

How to do that?

I've tried the line below without success (no errors in the console but the page does not render anymore):

page.css = "mainButton { backgroundColor: red }";

2 Answers 2

4

A simple solution would be to get an instance of the button using its id mainButton. Then changing the css or the View instance's backgroundColor property.

For example say you have this event on the tap event for the button:

function changeColor(args) {
   var btn = args.object;
   btn.backgroundColor = "#3489db";
}

In your xml:

<Button tap="changeColor" class="whatever" />

There are plenty of other approaches on when to execute but that should help you figure it out :)

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks. This works when I tap the button, however, I would like to change color without the click. Explaining better, I have a variable that has a new color, when the page loads, it should read this variable and set the mainButton to the new color. Is it possible? I thought I could get the reference to the button via the "id" in the XML file but this seems not to be working.
Yep - you can get the button with it's id during any event after it's initialized :) You mention page loads - the page in nativescript has many events loaded being one. So add an event to the page load and then you'd get the button by its ID and then set the property for backgroundColor. Does that make sense?
Unfortunately I am not sure how to do that. I am using the regular template and I am trying to add code inside the function createViewModel(). How could I get the element by its id?
I got the results I wanted (not necessarily the best way) adding this in the page: page.addCss(".btn_MainColor { background-color: "+fbMain+" }");
1

You can do that directly in your css file like this

Button {
  background-color: red;
}

or

.button-class {
   background-color: red;
}

and you can also update the highlight-color too

Button:highlighting {
   background-color: green;
}

and you can use the style property in js/ts and dont forget to import Color from tns-core-modules/color

buttonInstance.style.backgroundColor = new Color("#00FF00");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.