Search code examples
cssangularcss-variablesangular12

Inject CSS variable names that come form the server (Angular 12)


I'm trying to find the best solution to inject css variables into angular application (currently using Angular 12).

This is the code I'm using:

 private injectStyles(data: any) {
    const styles = this.document.createElement('STYLE') as HTMLStyleElement;
    styles.id = 'dynamic-css';

    this.test = `:root {      
      --main-bg-color: black;
    }`;
    
    styles.innerHTML = this.test;
    this.renderer.appendChild(this.document.head, styles);
}

This code is being executed on app.component.ts file and this works quite well, i can use this css variable throughout the whole application. What I'm trying to achieve now is to extend the this.test Object with data that comes from the server and apply these custom css values that were set on my Visual settings module before.

Css variables must not have "" quotes. "--button-color": "#a86c6c" (this is what I get from the server) and I would like to inject this property without quotes on the this.test Object and I can't do that. Any ideas?

Any help is highly appreciated, Thanks.


Solution

  • Object.keys is your friend

     let dataString = '';
     Object.keys(data).forEach(key => {
        dataString += `${key}: ${data[key]};`
     });
     this.test = `:root {      
      --main-bg-color: black;
      ${dataString}
    }`;
    

    If needed, you may need to add quote to the value like this

    `dataString += `${key}: "${data[key]};"`