Search code examples
javascriptcssweb-componentstenciljs

How to set css variable in stenciljs shadow component via javascript


I have a shadow component in stenciljs like

@Component({
    tag: "digital-verification",
    styleUrl: "digital-verification.scss",
    shadow: true,
})

and I have some css variable like

:host {
  --app-primary-color: #488aff;
  --app-border-radius: 10px;
  --app-error-color: #EE320C;
}

Till now everything is working perfect and no issue.

Now I want to set this variables in the code like

document.querySelector(':root').style.setProperty('--app-primary-color', '#ffffff');

I tried

   document.querySelector(':host').style

and

document.querySelector(':root').style

and

document.querySelector(':root').shadowRoot.style

and

    document.querySelector(':root').root.style

and

@Element() el;

...
this.el.shadowRoot.querySelector(":host") // this is null

but I get compile error that Element doesn't have style

Wondering how should I see css variables in the code.

update

I did below code, and I can see value is set in console, but application color doesn't change

        document.documentElement.style.setProperty("--app-primary-color", "#ff0000");
        console.log(document.documentElement.style.getPropertyValue("--app-primary-color"));

Solution

  • In case somebody else has same issue

    I did the below steps and issue is resolved

    1- I deleted the below section

    :host {
      --app-primary-color: #488aff;
      --app-border-radius: 10px;
      --app-error-color: #EE320C;
    }
    

    2- defined a variable like below

    $primary-color : var(--app-primary-color, #488aff);
    

    3- in code set the css variable like below

     document.documentElement.style.setProperty("--app-primary-color", "#ffff00" , "important");
    

    Updated solution based on @Danny '365CSI' Engelman comment

    1- You can delete the below section if you want to variable be applied to all children or keep it if you want it to be applied only on this component

    :host {
      --app-primary-color: #488aff;
      --app-border-radius: 10px;
      --app-error-color: #EE320C;
    }
    

    2- define @Element() el: HTMLElement; in your component

    3- in code set the css variable like below

     this.el.style.setProperty("--app-primary-color", "#ffff00");