5

Why I can't get the css variable content in angular?

I add variable in style.css as following:

:root {
  --foo: "string";
}

and try to get the value by getPropertyValue in app.component:

 ngOnInit() {
    const y = document.body.parentElement.style.getPropertyValue('--foo');
    console.log({ y }); // logs: "".
  }

codesandbox.io

I using Chrome last version.

Jon Sud
  • 10,211
  • 17
  • 76
  • 174
  • Have you tried this getComputedStyle(document.documentElement) .getPropertyValue('--foo') ? – Roman A. May 20 '21 at 07:24
  • thanks. with `getComputedStyle` it's works. but it's trigger paint event and it's impact performance – Jon Sud May 20 '21 at 07:26
  • If you know where it is set use that element to get the property otherwise I think you have to use @RomanA suggestion if the element you are looking at is not the one that set the property. – A Haworth May 20 '21 at 07:49
  • 2
    As the others have suggested, the `style` property only contains the CSS that is defined via the [`style` attribute](https://developer.mozilla.org/en-US/docs/Web/API/ElementCSSInlineStyle/style#getting_style_information). – Crafted Pod May 20 '21 at 07:57
  • check [this](https://stackoverflow.com/questions/48760274/get-all-css-root-variables-in-array-using-javascript-and-change-the-values) for another solution. basically manipulating `document.styleSheets[x].cssRules[y]` – lastr2d2 May 20 '21 at 08:07

0 Answers0