How to Change the Background color in Ionic after 10 seconds

Hi @Abdulkhader,

Here’s a simple way to do what you’re looking for.

First, consider abstracting the problem a little more. Instead of changing the color, think of it as changing the CSS class. That makes the problem easier (no DOM interaction), and it makes your code more reusable (it’s no longer just for the background color).

To swap classes easily, we use square bracket notation:

<ion-content padding [class]='GetColorName()'>

And to do this every 10 seconds, we use setInterval with a lambda function. Use a lambda function to keep your scoping of the keyword this set properly. See here for another example.

Look into Observables, because that will probably be a good solution as well.

home.html

<ion-header>
	<ion-navbar>
		<ion-title>
			Ionic Blank
		</ion-title>
	</ion-navbar>
</ion-header>

<ion-content padding [class]='GetColorName()'>
	<button ion-button (click)="ChangeColorManually(1)">Kermit</button>
	<button ion-button (click)="ChangeColorManually(2)">Rowlf</button>
	<button ion-button (click)="ChangeColorManually(3)">Ms. Piggy</button>
</ion-content>

home.ts

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';

@Component({
	selector: 'page-home',
	templateUrl: 'home.html'
})
export class HomePage {

	private _colorChoice : number;
	private _swapTimeMS : number;
	
	constructor(public navCtrl: NavController) {
		this._colorChoice = 1;
		this._swapTimeMS = 10000;		// 10 seconds
		
		setInterval( () => {
			this.ChangeColors();
		  }, this._swapTimeMS);
	}

	ChangeColors() {
		this._colorChoice++;
		if (this._colorChoice > 3)
			this._colorChoice = 1;
	}

	ChangeColorManually(choice: number) {
		this._colorChoice = choice;
	}

	GetColorName() {
		if (this._colorChoice == 1)
			return "kermit";
		else if (this._colorChoice == 2)
			return "rowlf";
		else if (this._colorChoice == 3)
			return "msPiggy";
		
		return "";
	}
}

home.scss

page-home {

    .kermit {
        background-color: #00FF00;
    }

    .rowlf {
        background-color: #8B4513;
    }

    .msPiggy {
        background-color: #FF0088;
    }
}

Good luck,
Ryan