Sampath
Sampath

Reputation: 65860

Change element css property dynamically

I need to dynamically set the background image. Since ion-content is an element how can I do that? If it is a css class then I can do like so

[class]="cssClassName" and I can change the class name inside the ts file. But here how can I do that?

.ts

ngOnInit() { this.init(); }

init() {
    switch (environment.hotelEnvironment.hotelName) {
      case "com1":
       // has back ground
        break;
      case "com2":
       //no back ground
        break;
      default:
    }
  }

.html

<ion-content>

</ion-content>

.scss

ion-content {
    --background: url('/assets/img/com/background/background.png') no-repeat 100% 100%;

}

Upvotes: 1

Views: 1290

Answers (4)

talhature
talhature

Reputation: 2165

You can have two different css classes with the desired backgrounds. Having a class variable to hold the class name that you switch in your init method and binding it to the ion-content component should do it.

<ion-content [ngClass]="hotelBackground">
  ...
</ion-content>

ngOnInit() { this.init(); }
hotelBackground: string;
init() {
    switch (environment.hotelEnvironment.hotelName) {
      case "com1":
       this.hotelBackground = 'com1';
       break;
      case "com2":
       this.hotelBackground = 'com2';
       break;
      default:
    }
  }

.scss

.com1 {background: url('/assets/img/com/background/background.png') no-repeat 100% 100%; } 

.com2{ background: none} 

Upvotes: 1

Sampath
Sampath

Reputation: 65860

I have achieved it like so:

Note: Very important part here is this ion-content.background-image

.scss

ion-content.background-image {
    --background: url('/assets/img/com/background/background.png') no-repeat 100% 100%;       
}

.ts

ngOnInit() { this.init(); }

init() {
    switch (environment.hotelEnvironment.hotelName) {
      case "com1":
        this.cssClassName = "";
        break;
      case "com2":
        this.cssClassName = "background-image";
        break;
      default:
    }
  }

.html

 <ion-content [ngClass]="cssClassName">

    </ion-content>

Upvotes: 0

Levi
Levi

Reputation: 859

use [class.<YOUR_CLASS_NAME>] = "<SOME CONDITION>" See this its answered here

Angular: conditional class with *ngClass for reference

Upvotes: 1

DCR
DCR

Reputation: 15657

something like this might work:

$(document).ready(function() {
  $("button").click(function() {
    $(".content1").toggleClass("active");
  });
});
.content1.active {
  background-image: url('../images/light.png');
  background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button>Clicky</button>
<div class="content1"> Hello </div>

Upvotes: -1

Related Questions