【问题标题】:Can I change ion-item custom css property --background dynamically in Ionic 4?我可以在 Ionic 4 中动态更改 ion-item 自定义 css 属性 --background 吗?
【发布时间】:2020-02-10 21:18:18
【问题描述】:

我们如何设置动态背景颜色?我需要基于数组渲染 ion-item 元素。我需要在 ngFor 循环中设置背景颜色,来自数组中的每个值。有什么想法吗?

我尝试过这样的事情。但它不起作用

<ion-list *ngFor="let shift of shifts">
     <ion-item [style.--background]="'shift.color'">{{ shift.color }} qwe</ion-item>
</ion-list>

【问题讨论】:

标签: angular ionic-framework ionic4


【解决方案1】:

试试这个,

<ion-list *ngFor="let shift of shifts">
     <ion-item [style.background]="shift.color"> {{shift.color}} qwe</ion-item>
</ion-list>

【讨论】:

  • 对于 ionic 4 中的 ion-item 这不起作用我需要更改自定义 css 变量 --background 以更改背景颜色
【解决方案2】:

我相信你可以通过改变它来做到这一点,

<ion-list *ngFor="let shift of shifts">
     <ion-item [color]="shift.color">{{ shift.color }} qwe</ion-item>
</ion-list>

【讨论】:

    【解决方案3】:

    我也为您创建了一个堆栈闪电战,以展示这一切是如何运作的: https://stackblitz.com/edit/using-ngstyle-and-ngclass

    上面的答案肯定会起作用,但是让我告诉你,还有其他方法可以做到这一点,不管你是静态的还是动态的,都会以动态的方式使用。

    /* Your way (mistake is that you added -- before the string and you used shift.color with '' so it gets passed as string) */
    <ion-list *ngFor="let shift of shifts">
         <ion-item [style.background]="shift.color">{{ shift.color }}qwe</ion-item>
    </ion-list>
    
    /* using ngStyle (you can add a fall back color if shift.color doesn't exist) */
    <ion-list *ngFor="let shift of shifts">
         <ion-item [ngStyle]="{'background-color': shift?.color ? shift.color : 'red' }">color</ion-item>
    </ion-list>
    
    /* another way is to use ngClass where you can define classes for the color codes and from the backend you get class names which I believe are more readable and you can remember */
    <ion-list *ngFor="let shift of shifts">
         <ion-item [ngClass]="{'color-green': shift?.color}">color</ion-item>
    </ion-list>
    

    【讨论】:

    • 这不适用于 Ionic 4,因为它使用 shadow dom 并且不能动态更改 scss 变量。
    猜你喜欢
    • 1970-01-01
    • 2015-10-24
    • 1970-01-01
    • 2019-05-28
    • 2019-10-14
    • 2019-12-06
    • 2019-06-03
    • 2020-04-17
    • 2021-08-04
    相关资源
    最近更新 更多