【问题标题】:Is it possible to use styles from an Angular service in scss?是否可以在 scss 中使用来自 Angular 服务的样式?
【发布时间】:2021-09-05 20:24:18
【问题描述】:

我有一个 change-color.service.ts 具有以下内容:

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

现在我想将声明添加到我的 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;
}

#fff 替换为change-service 中的firstDesignFontColor。你知道我如何创建这个依赖吗?这可能吗?

【问题讨论】:

  • 你为什么不根据你的每个条件创建类?从服务获取您的类名并将类分配给元素取决于条件。

标签: css angular typescript sass


【解决方案1】:

不,那是不可能的。有可能的是使用样式绑定。

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

【讨论】:

  • 是的,我也这样做了。我的代码中有一些我无法通过模板更改的 scss 类(如我的示例中)。以为您可以以某种方式将服务导入 scss 文件,然后在适当的位置调用变量。
  • @and.neo2020 我刚刚意识到可能有一种方法适合您使用 css 变量。请参阅我的其他答案。
【解决方案2】:

实际上有一种方法可以使用 css 变量来实现它,我将在此处发布作为第二个答案。

您可以从 JavaScript 代码更改 css 变量,因此,如果您像以下简化示例一样为您的类使用变量:

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

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

然后你可以从你的 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);
    }
}

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

【讨论】:

  • 我刚刚阅读了您的第一个答案,就像,css 变量怎么样,然后我看到了您的第二个答案:D
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-02-13
  • 1970-01-01
  • 2011-05-28
  • 1970-01-01
  • 2021-02-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多