Blog>
Snippets

Angular Theming with CSS Variables and SASS

Integrate SASS with Angular's styles to combine the power of preprocessor features and CSS variables for theming. Show how to use SASS functions to modify theme colors.
$primary-color: #007bff;
$secondary-color: #6c757d;
$success-color: #28a745;

:root {
  --primary: #{$primary-color};
  --secondary: #{$secondary-color};
  --success: #{$success-color};
}

@mixin theme-colors($theme-map) {
  @each $color-name, $color-value in $theme-map {
    --#{$color-name}: #{adjust-color($color-value, $lightness: -20%)};
  }
}

@include theme-colors((
  primary: $primary-color,
  secondary: $secondary-color,
  success: $success-color
));
This SASS code defines a set of color variables and creates corresponding CSS variables within the :root pseudo-class. It also includes a mixin to adjust these colors and applies it to the theme colors.
import { Component, HostBinding } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `\
    <div class="container">
      <h1>Welcome to Angular Theming!</h1>
      <button class="btn-primary">Primary Button</button>
      <button class="btn-secondary">Secondary Button</button>
    </div>
  `,
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  @HostBinding('class') className = '';

  toggleTheme(isDark: boolean) {
    this.className = isDark ? 'theme-dark' : '';
  }
}
This Angular component uses HostBinding to conditionally apply a CSS class based on the theme selected. It binds to the 'class' property of the host element and toggles between dark and default themes.