Blog>
Snippets

Defining CSS Variables in Angular Component Styles

Show how to define CSS variables within an Angular component's styles section, setting a theme base for individual components that can be easily manipulated.
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-theme-component',
  template: `<div class=
This code snippet begins by importing the necessary Angular core components. The @Component decorator defines the 'app-theme-component' which will use CSS variables within its styles.
themed-component
Inside the template, a div element is given a class name that will be associated with the styles defined with the CSS variables.
>This is a themed component</div>`,
  styles: [`
    .themed-component {
      --primary-color: #336699; /* Define the primary color variable */
      --secondary-color: #aabbcc; /* Define the secondary color variable */
      background-color: var(--primary-color);
      color: var(--secondary-color);
    }
  `]
})
export class ThemeComponent implements OnInit {

  constructor() { }

  ngOnInit(): void {
  }

}
The styles array contains a backtick template literal where the CSS variables --primary-color and --secondary-color are defined for the themed-component class. The background and text color of this component are then set using these CSS variables. Lastly, the ThemeComponent class is exported, implementing the OnInit interface.