简体   繁体   English

是否可以在 scss 中使用来自 Angular 服务的样式?

[英]Is it possible to use styles from an Angular service in scss?

I have a change-color.service.ts that has the following:我有一个 change-color.service.ts 具有以下内容:

public defaultStyles = {
    firstDesignBackgroundColor: '#a31329',
    firstDesignFontColor: '#ffffff',
    secondDesignBackgroundColor: '#d1cfcfff',
    secondDesignFontColor: '#000000'
  };

now I will like to add to my style.scss for the statement现在我想添加到我的 style.scss 声明

:host ::ng-deep th span#optimize-checkbox-header .mat-checkbox label.mat-checkbox-layout .mat-checkbox-inner-container.mat-checkbox-inner-container-no-side-margin .mat-checkbox-frame {
  border: 2px solid #fff !important;
}

replace the #fff with firstDesignFontColor from the change-service .更换#ffffirstDesignFontColorchange-service Do you know how I can create this dependency?你知道我如何创建这种依赖吗? Is this possible at all?这可能吗?

There is actually a way to realize it with css variables that I will post here as a second answer.实际上有一种方法可以使用 css 变量来实现它,我将在这里发布作为第二个答案。

You can change css variables from JavaScript code, so if you use variables for your class like this simplified example:您可以从 JavaScript 代码更改 css 变量,因此如果您像这个简化示例一样为您的类使用变量:

:root {
  --bg-color: red;
}

.test {
  background-color: var(--bg-color);
}

then you can change this from your ChangeColorService然后你可以从你的 ChangeColorService 改变这个

interface Colors {
  background: string;
}

@Injectable()
export class ChangeColorService {
    colors$ = new BehaviorSubject<Colors>({ background: 'red' });

    constructor(@Inject(DOCUMENT) private document: Document) { }

    change(colors: Colors) {
      const root = this.document.documentElement;
      root.style.setProperty('--bg-color', colors.background);
      this.colors$.next(colors);
    }
}

Full example: https://stackblitz.com/edit/angular-change-css-variable?file=src/app/app.component.ts完整示例: https : //stackblitz.com/edit/angular-change-css-variable?file=src/app/app.component.ts

No that's not possible.不,那是不可能的。 What is possible, is to use style bindings.可能的是使用样式绑定。

class YourComponent {
    styles: any;
    constructor(private color: ChangeColor) {}
    ngOnInit() { this.styles = this.color.defaultStyles; }
}
  <div [style.background-color]="styles.firstDesignBackgroundColor"></div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM