Dynamically change color in Ionic 2

14,074

Solution 1

<ion-icon name="notifications" [color]="color">

Hope this works

Solution 2

.HTML file Code to set background color

<ion-col col-12 *ngFor="let item of newsArray" class="dir-col" >
          <div class="cell-dot" [ngStyle]="{'background-color': item.colorCode}"> 
     </div>
</ion-col>

.ts file code to set dynamic color code from web service

  this.totalSearchRecord = data["TotalNewsRecords"]
      for (let news of data["records"]) {
        this.newsArray.push({
          newsId: this.serviceProvider.checkNull(news['id']),
          newsTitle: this.serviceProvider.checkNull(news['PressReleaseTitle']),
          newsDes: this.serviceProvider.checkNull(news['PressReleaseShortDes']),
          newsDate: this.serviceProvider.checkNull(news['PressReleaseDate']),
          newsMonth: this.serviceProvider.checkNull(news['PressReleaseMonth']),
          alias: this.serviceProvider.checkNull(news['Alias']),
          colorCode:'#FFFFFF',
        });
      }
Share:
14,074
user2739655
Author by

user2739655

Updated on June 09, 2022

Comments

  • user2739655
    user2739655 almost 2 years

    Based on some condition, I am trying to set the color value of an element.

    So, in my TS file, I have taken a variable called color that I am setting as

      if(this.value>0) this.color="#ffc000!important";
    

    In my HTML file, I have tried setting this color in the following ways

    <ion-icon name="notifications" [style.color]="color">
    

    as well as using ngstyle

    <ion-icon name="notifications" [ngStyle]="{'color': color}">
    

    None of these are working. What am I doing wrong or what is the right way to do this?