【问题标题】:Changing background colour of ion-navbar using *ngIf使用 *ngIf 更改 ion-navbar 的背景颜色
【发布时间】:2019-04-20 21:34:33
【问题描述】:

使用 ion-navbar 和 Firebase 数据库。

我希望看到的是,根据 Firebase DB 中的“颜色”子项,将显示不同的 ion-navbar 背景颜色。

我目前正在使用 *ngIf 来解决我的问题,但我无法让它发挥作用。无论 this.selectedItem.color 的颜色如何,它都会一直显示蓝色背景(#85dec8,最后一个 *ngIf 语句)。

我的代码:

   <ion-navbar class="bar">
    <ion-title class="bar">{{selectedItem.name}}</ion-title>
    <style *ngIf="selectedItem.color=='#ffce4e'">
      .bar {
        background-color: #ffce4e;
      }
    </style>
    <style *ngIf="selectedItem.color=='#f55f7c'">
        .bar {
          background-color: #f55f7c;
        }
    </style>
    <style *ngIf="selectedItem.color=='#85dec8'">
        .bar {
          background-color: #85dec8;
        }
    </style>
  </ion-navbar>
  

任何帮助将不胜感激!

【问题讨论】:

    标签: html css ionic-framework firebase-realtime-database


    【解决方案1】:

    使用[style.background-color]

       <ion-navbar class="bar">
             <ion-title class="bar" [style.background-color]="selectedItem.color">{{selectedItem.name}}</ion-title>
      </ion-navbar>
    

    在此处查看示例:https://stackblitz.com/edit/ionic-z2pb8w?file=pages%2Fhome%2Fhome.html

    或者你可以使用[ngClass],那么你将不得不使用css

       <ion-navbar class="bar">
             <ion-title class="bar" [ngClass]="{'bar': selectedItem.color=='#ffce4e', 'barA': selectedItem.color=='#f55f7c', 'barB':selectedItem.color=='#85dec8'}">{{selectedItem.name}}</ion-title>
      </ion-navbar>
    

    在css中:

      .bar {
        background-color: #ffce4e;
      }
    .barA {
      background-color: #f55f7c;
    }
    
    .barB {
      background-color: #85dec8;
    }
    

    这是一个例子: https://stackblitz.com/edit/ionic-3kgulw?file=pages%2Fhome%2Fhome.html

    【讨论】:

    • 嗯,我完全复制了您的代码,但它只显示了“84dec8”(蓝色)颜色的背景颜色。例如,#ffce4e selectedItem 甚至没有背景颜色。
    • 另外,看起来 [ngStyle.color] 不是 ion-title 或 ion-navbar 的已知可用属性
    • 抱歉,它仍然无法正常工作。也许这是 Ionic 的错误?
    • 这是一件很奇怪的事情,但它再次只显示最后一个类 (.barB .toolbar-title) 的 css 更改。这真的很令人沮丧。
    【解决方案2】:

    编辑 你应该在这里使用ngClass

      <style>
      .bar1 {
        background-color: #ffce4e;
      }
      .bar2 {
          background-color: #f55f7c;
      }
      .bar3 {
          background-color: #85dec8;
      }
     </style>
     <ion-navbar [ngClass]="{'bar1' : selectedItem.color=='#ffce4e', 'bar2' : 
     selectedItem.color=='#f55f7c', 'bar3' : selectedItem.color=='#85dec8'}">
     <ion-title class="bar">{{selectedItem.name}}</ion-title>
     </ion-navbar>`
    

    【讨论】:

    • 您好,谢谢,但是您的方法不起作用。不幸的是,我完全使用了你的方法,它没有改变任何东西。
    • @caroline 显然我错过了结尾的} 我已经编辑了它,您还需要在&lt;ion-title&gt; 标签上添加相同的条件。
    • 嗨@Jazib,我已经按照你的建议做了,但它又不起作用。太不幸了..
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-29
    • 2019-08-01
    • 2019-06-03
    • 2015-10-24
    • 1970-01-01
    • 1970-01-01
    • 2016-07-13
    相关资源
    最近更新 更多