Blog>
Snippets

Angular Theming with CSS Variable Fallbacks

Provide fallback values for CSS variables within Angular templates to ensure compatibility and default styling when custom properties are not set.
import { Component, HostBinding } from '@angular/core';

@Component({
  selector: 'app-my-component',
  template: `
    <div class="themed-element">
      This element will be styled based on the theme.
    </div>
  `,
  styles: [
    `:host(.themed-element) {
      --primary-color: var(--custom-primary-color, #007bff);
      --secondary-color: var(--custom-secondary-color, #6c757d);
      background-color: var(--primary-color);
      color: var(--secondary-color);
    }`
  ]
})
export class MyComponent {
  // You can bind CSS Variables with host binding to set up themes dynamically
  @HostBinding('style.--custom-primary-color') primaryColor = '';
  @HostBinding('style.--custom-secondary-color') secondaryColor = '';

  constructor() {
    // Assign default fallback values if not provided
    this.primaryColor = this.primaryColor || '#007bff'; // Default primary color
    this.secondaryColor = this.secondaryColor || '#6c757d'; // Default secondary color
  }
}
This Angular component uses CSS variable fallbacks within the scoped styles of the component. The `--primary-color` and `--secondary-color` variables are defined with fallbacks. If those variables are not set, the provided default colors are used. This is useful when using theming in Angular applications to ensure compatibility across browsers that do not support CSS variables and to provide default styling. Additionally, the component uses `HostBinding` to dynamically set CSS variables based on component logic.