6

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.

5
  • Have you tried this getComputedStyle(document.documentElement) .getPropertyValue('--foo') ? Commented May 20, 2021 at 7:24
  • thanks. with getComputedStyle it's works. but it's trigger paint event and it's impact performance Commented May 20, 2021 at 7: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. Commented May 20, 2021 at 7:49
  • 3
    As the others have suggested, the style property only contains the CSS that is defined via the style attribute. Commented May 20, 2021 at 7:57
  • check this for another solution. basically manipulating document.styleSheets[x].cssRules[y] Commented May 20, 2021 at 8:07

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.