Ion-page dynamic background-color


#1

How can I change the style of my ion-page in my component?

Per instance ionic2 generates in <ion-page> a class with the name of our page/component:

<ion-page class="subjects-page">

Depending in some action in my component, I need to change its background color.

How can I achieve that?


#2

You can assign classes by adding watcher right to the <ion-content> directive and style any children in css.

You can assign different classes with different values:
<ion-content [ngClass]="{'featured': classWatcher == 'featured', 'hidden': classWatcher == 'hidden', 'blue': classWatcher == 'blue'}"> ... </ion-content>
etc.


#3

In JS/TS you first need to create default or empty variable
let classWatcher = 'blue'
and then change in any actions/functions:

changeClass(newState){ classWatcher = newState; }


#4

Sorry but your exemple is for ion-content - I’m talking about ion-page which is auto-generated by Ionic.


#5

Sure, but in most cases actual background that you see is your ion-content,
could you please show the part of your layout / design or what you want to achieve?


#6

Just tested, if you will actually assign a background to the ion-page element itself that will break all default visual behaviour


#7

first of all thank you for the effort.

now, sorry, I have to disagree with you - setting the background in the ion-page does not break the default visual behavior because I tested it with static background color.

I could do this within ion-content, it works also, but in my case would be more or less a hack, as every page of the app has a gradient background color from the top to the bottom. this means, same color for tollbar, navbar, tabbar, etc…


#8

I found the solution,

I had to Import Content

import {NavController, Content} from "ionic-angular";

And then inject and use it like that:

constructor(private nav: NavController, private content: Content) {
    this.myService.doSomething().then(() => {
        this.content.addCssClass("className"); // Here we go
    });
}