Last week, I needed to access a CSS variable in an Angular template to configure a Chart.js chart.

You can use @HostBinding to achieve this.

What is @HostBinding?

@HostBinding is an Angular decorator that allows developers to bind a directive property to a host element property. It is used to set a property value on the host element of a component, in this case the component’s root element. This decorator is used in conjunction with the host property of the @Directive decorator to define a host element.

Here’s an example of how to use @HostBinding to access a CSS variable in your Angular component.

Define your CSS variable in your .css file:

:root {
  --primary-color: #007bff;

In your component, create a @HostBinding property to bind the value of your CSS variable to a CSS custom property:

primaryColor = getComputedStyle(document.documentElement)

This code binds the value of the --primary-color CSS custom property to the primaryColor property of your component.

Now you can access the variable in your Angular component to style your chart:

datasets = [
      label: 'Dataset 1',
      data: Utils.numbers(NUMBER_CFG),
      borderColor: this.primaryColor,
    // more datasets

If you change your styles in the .css file, your Angular component will pick it up and use the correct color.

Further Reading