簡體   English   中英

在Ionic 2中動態改變顏色

[英]Dynamically change color in Ionic 2

基於某些條件,我試圖設置元素的顏色值。

所以,在我的TS文件中,我采用了一個名為color的變量,我將其設置為

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

在我的HTML文件中,我嘗試通過以下方式設置此顏色

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

以及使用ngstyle

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

這些都不起作用。 我做錯了什么或者做到這一點的正確方法是什么?

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

希望這有效

.HTML文件用於設置背景顏色的代碼

<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文件代碼,用於從Web服務設置動態顏色代碼

  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',
        });
      }

參考

當我們傳遞我們想要在name屬性中使用的圖標的name離子會根據模式添加該圖標的類。 例如,如果你通過心臟:

<ion-icon name="heart"></ion-icon>

在iOS上它將是:

<ion-icon class="ion-ios-heart"></ion-icon>

對於材料設計模式,它將是:

<ion-icon class="ion-md-heart"></ion-icon>

這樣我們就可以使用類名為它們添加CSS屬性。

在你的scss文件中,

.ion-md-heart{
        color: red !important;
    }
.ion-ios-heart{
        color: red !important;
    }

希望這有幫助,它對我有用。

在Angular 2 / Ionic 2中,一種更改對象顏色的簡單方法是使用theme / variables.scss文件。

// Named Color Variables
// --------------------------------------------------
// Named colors makes it easy to reuse colors on various components.
// It's highly recommended to change the default colors
// to match your app's branding. Ionic uses a Sass map of
// colors so you can add, rename and remove colors as needed.
// The "primary" color is the only required color in the map.

$colors: (
  primary:    #488aff,
  secondary:  #32db64,
  danger:     #f53d3d,
  light:      #f4f4f4,
  dark:       #222,
  my-special-color:   #ffcc55,
);

現在,要在ionic2頁面中動態更改顏色,可以通過將顏色綁定到HTML部分中的變量來實現

<button [color]="myBtnColor">MyButton</button>

在你的TypeScript部分

import { ..., ChangeDetectorRef, ... } from '@angular/core';
...
export class MyComponent {
  myBtnColor = "secondary"
  constructor(private changeDetectorRef:ChangeDetectorRef) {}
  ...
  function changeColorDynamicaly() {
    myBtnColor = "my-special-color";
    this.changeDetectorRef.detectChanges();
  }
  ...
}

在我的例子中,ChangeDetectorRef用於查看視圖中反映的實際更改。 視圖無效以進行更新。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM