首页 > 解决方案 > Ionic - custom colors from SASS file in ngStyle

问题描述

In my Ionic project, in my src/theme/variables.scss, below the $colors group, I have another group of colors $buttonColors which looks like this:

$colors: (
  primary:    #488aff,
  secondary:  #32db64,
  danger:     #f53d3d,
  light:      #f4f4f4,
  dark:       #222
);
$buttonColors: (
  sampleRed: #A92A0E,
  sampleBlue:  #162C60
);

In my .css file I can use the second group of colors like this:

.element {
  color: color($buttonColors, sampleRed, base);
}

But if I want to use the code from above in [ngStyle]="{'color' : 'color($buttonColors, sampleRed, base)'}" - this would not work.

And in my case I want to use this color specifically in ngStyle. How can I reference to this color correctly in ngStyle?

标签: angulartypescriptionic-frameworkcolorssass

解决方案


在组件文件中:

import {Sanitizer} from '@angular/core';

export class MyCass {
      sanitizer: Sanitizer;
      myColor = '#444444';

constructor(_sanitizer: Sanitizer) {
        this.sanitizer = _sanitizer;
    }

在 HTML 文件中:

<ion-title [attr.style]="sanitizer.bypassSecurityTrustStyle('--color: ' + myColor)"></ion-title>

它对我有用。但是你必须使用 ionic 4 CSS 变量。


推荐阅读