Change slide background color dynamically

I am using the ionic 2 slide component, and for each slide I want a different background color. So, my slider constructor look like this:

constructor(nav: NavController, param: NavParams) {
  this.nav = nav;
  this.param = param;

  this.slides = [
    {
      title: "Welcome to the Docs!",
      description: "The <b>Ionic Component Documentation</b> showcases a number of useful components that are included out of the box with Ionic.",
      image: "img/phone.png",
      color: "#2662F7",
    },
    {
      title: "What is Ionic?",
      description: "<b>Ionic Framework</b> is an open source SDK that enables developers to build high quality mobile apps with web technologies like HTML, CSS, and JavaScript.",
      image: "img/phone.png",
      color: "#FD4B4B",
    },
    {
      title: "What is Ionic Platform?",
      description: "The <b>Ionic Platform</b> is a cloud platform for managing and scaling Ionic apps with integrated services like push notifications, native builds, user auth, and live updating.",
      image: "img/phone.png",
      color: "#4BC14B",
    }
  ];
}

and my html code looks like this:

<ion-slides pager loop="true" autoplay="true">

  <ion-slide style="background-color:{{slide.color}}" *ngFor="#slide of slides">

      <ion-row class="ontop">
        <ion-col class="col1">
          <button class="signin">Sign in</button>
        </ion-col>
        <ion-col class="col2">
          <button class="skip">Skip</button>
        </ion-col>
      </ion-row>


    <h2 class="slide-title" [innerHTML]="slide.title"></h2>
    <p class="slide-description" [innerHTML]="slide.description"></p>
    <img [src]="slide.image" class="slide-image" />
  </ion-slide>

</ion-slides>

This works fine in chrome, the background color changes as I want to. But when I compile the app on Android and iOS, it doesnā€™t work. All the styles in the app goes crazy.

How is the correct way to do this? so it works everywhere.

Thanks

4 Likes

Have you tried using ngStyle?

<ion-slide *ngFor="#slide of slides" [ngStyle]="{'background-color': slide.color}">

https://angular.io/docs/js/latest/api/common/NgStyle-directive.html

15 Likes

Thanks a lot, it worked!

3 Likes

Buen dia tengo el problema con [ngStyle] ="{ā€˜background-imageā€™ : ā€˜url({{item.url}})ā€™}", por favor ayuda

thanks, it worked. :grinning:

Use this:
[ngStyle] ="{ā€˜background-imageā€™ : 'url(' + item.url + ')'}"