MoreDroid Inc.
MoreDroid Inc.

Reputation: 21

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;
    }
}

Upvotes: 2

Views: 2568

Answers (1)

Sampath
Sampath

Reputation: 65870

You can do it as shown below:

Here is the working stackblitz

.ts

  isChanged: boolean = false;
  constructor(public navCtrl: NavController) {
  }

 color() {
   this.isChanged = true;
 }

.scss

.classname{
  background-color: red;
}

.html

<ion-content padding [ngClass]="{'classname': isChanged }">
    <h2>Welcome to Ionic!</h2>
    <button ion-button color="secondary" (click)="color()">Dynamic Color</button>
</ion-content>

Upvotes: 2

Related Questions