Blog>
Snippets

Responsive Theming with Angular and CSS Variables

Showcase responsive theming techniques by changing CSS variables based on different breakpoints using Angular's HostListener to detect window resize events.
import { HostListener, Component, Renderer2 } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  constructor(private renderer: Renderer2) {
    this.updateCSSVariables(window.innerWidth);
  }

  @HostListener('window:resize', ['$event'])
  onResize(event: Event) {
    this.updateCSSVariables((event.target as Window).innerWidth);
  }

  updateCSSVariables(width: number) {
    const root = document.documentElement;
    if (width < 600) {
      // Small devices
      root.style.setProperty('--primary-color', 'blue');
      root.style.setProperty('--font-size', '14px');
    } else if (width >= 600 && width < 900) {
      // Medium devices
      root.style.setProperty('--primary-color', 'green');
      root.style.setProperty('--font-size', '16px');
    } else {
      // Large devices
      root.style.setProperty('--primary-color', 'red');
      root.style.setProperty('--font-size', '18px');
    }
  }
}
The AppComponent listens for the window resize event and then calls the updateCSSVariables method to set different CSS variable values based on window width breakpoints. This allows for responsive theming by changing styles dynamically according to the screen size.