Change the background color dynamically in ionic 3

Hello I wanted to know how I can change the background color, with a button and tried this without any positive results:

what I try to do is that with a button I change the color of my background, for example from white to red

I’m trying this way but it does not work

HTML:

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

<ion-content padding [ngClass]="{ classname:false }">
    The world is your oyster.
    <p>
        If you get lost, the <a href="http://ionicframework.com/docs/v2">docs</a> will be your guide.
    </p>

    <ion-buttons (click)="color()">
        <button>
        Hola
      </button>
    </ion-buttons>
</ion-content>

TS

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

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

  classname = false;
  constructor(public navCtrl: NavController) {

  }

  color() {
    console.log('Hola');
    this.classname = true;
  }

}

My SCSS.

page-home {
    .classname {
        Background: red;
    }
}

hey, you can put this code
in home.html

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

<ion-content padding [ngClass]="{'bg-red': changeColor}">
    The world is your oyster.
    <p>
        If you get lost, the <a href="http://ionicframework.com/docs/v2">docs</a> will be your guide.
    </p>

    <ion-buttons (click)="color()">
        <button>
        Hola
      </button>
    </ion-buttons>
</ion-content>

in your home.scss

page-home {
 .bg-red{
       background-color: red;
   }
}

in your home.ts


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

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

  changeColor = false;
  constructor(public navCtrl: NavController) {

  }

  color() {
    console.log('Hola');
    this.changeColor = true;
  }

}
1 Like