Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set sass variable value in Angular 7

I have been working with angular for the last few weeks, and now I have a requirement to dynamically style a public site. The site admin set various color codes as well as a logo image from admin in a database. These will be reflected when the Public Site opens.

As I am from an asp.net background, previously what I would do is on master page load, take values from the DB and write them into a .less file, and let java-script library take care of it. It's simple there.

But for my current situation, I am using sass, and I am not able find a way to write variables into a .scss file.

I just learn a new thing APP_INITIALIZER from here ,but ultimately this post not showing how to write in the .scss file.

I am actually thinking this with my asp.net knowledge,but may be I am wrong ,or there are another way of implementation.

I want a simple solution ,what we do in asp.net I want to achieve this in same way.

  1. Take variable value from DB via api,when application loading for first time.

  2. Write values in SASS variable file .

  3. After that SASS will take care of this and we get result as expected .

Please give some suggestion or example ,to start with .

Thanks.

like image 773
kuntal Avatar asked Feb 06 '19 17:02

kuntal


3 Answers

While @Cold Cerberus has suggested a good approach and is right about maintaining style related things at front-end, i am suggesting some ways for this.

As you said you want various colour combination,you can use Conditional CSS of SASS.

body[theme="theme1"] {
   // theme 1 css
}

body[them="theme2"] {
    // theme 2 css
}

You can use sass theme map along with conditional css.

Just update your attribute and theme will be applied automatically.

    themeChange() {
    const dom = document.querySelector('body');
    dom.theme = theme1;    // change theme here
    }

If you are very particular about some element style which should be updated from back-end (like colour code) you can use ng-style along with theme approach.

<some-element [ngStyle]="{'font-style': styleExp}">...</some-element>

You have to use smart combination of above in order to fulfill your requirement.

like image 52
Rajat Gupta Avatar answered Oct 17 '22 15:10

Rajat Gupta


First of all, in ASP .NET, it might be not bad to have a db hold CSS rules and other static assets. This is because it is a Server Side Rendering framework, so it kinda makes sense.

On the other hand, in Angular, it is client side (with the exception of Angular Universal, but you'll still have to expect working in similar approaches). Even with translations (i18n or custom), in Angular world, it is most likely stored on the front end (i18n .json files) and not from the back (db or so).

So you'll have to go and have your theme's stored in a certain manner you prefer and make your way to switching between them dynamically with Angular. You can of course store the keys/variables for the styles/themes but your actual CSS code is still stored on .css files.

Try to see this simple example from CSS vars in use while dynamically setting app theme (Angular). This is only just one way and there are lots of ways to do this and you might have to look for your personal preference.

UPDATE:

There might be erroneous implications of my answer above, but I'll leave it as is and just share one experience I had that is related to this topic.

I have worked on a webapp where the user can customize his theme via settings, likewise, The CSS rules aren't stored on DB, but the color values to be set on sass variables are. There was a special script where CSS scripts will be compiled (was returned on demand which made it a bit slow but a splash screen just saves your day, not AOT compiled) along with the custom values, which I don't have any idea how it was done. The same with translations, I also recently worked on a project where translations are from db, but there's a script to run for every release/deployment that generates and updates the .json files in the assets/i18n folder.

like image 22
Cold Cerberus Avatar answered Oct 17 '22 17:10

Cold Cerberus


As other answers explained, it is not possible to set SASS variables and process that on the client, as SASS is converted to plain CSS at build time and when app is running or in APP_INITIALIZER browser can process only CSS.

I see two options to achieve what you want.

Generally, you would have some base css for the app, and then you need to load the additional css based on admin settings. What needs to be considered from css point of view is that all css specificity in additional css should be greater than base css, because otherwise it won't override the base. That requires basic css knowledge so I won't go into details.

Method 1

Generate your additional css on server request. Load it when app is started from server URL. Reload it by js when admin change any settings.

  1. Define backend endpoint at address /additional.css (or it could be similar to /api/theme/custom-css) which will generate css out of database. For example you have background=red in db, then the endpoint should return
body {background-color: red;}
  1. Add <link id="additionalCss" rel="stylesheet" type="text/css" href="additional.css" /> in <head> of index.html. And that will be enough to make it work.
  2. To reload you can use different methods, but I believe this should work
document.getElementById('additionalCss').href = document.getElementById('additionalCss').href;

This will make new request to the server, server will execute DB -> css and return the updated css, which will be applied to the browser.

And if you want to be cool (or need to support big and complex themes) scss can be used. Backend should generate scss variable definitions out of database, then should use some server-side app to compile scss -> css, and then serve compiled css back to the client. But this will be overkill if additional css is simple enough.

One important consideration of this method is browser caching, because content behind additional.css is dynamic, but browser may cache it, not call the backend and serve outdated version.

Method 2

If you don't want or can't mess with the backend. Load settings from DB by some API endpoint in json, then generate css code on the client and apply it.

  1. Use HttpClient to get settings JSON and generate css as string out of it. For example server returns
{
  "background": "red"
}

then you convert this to string as

cssCode = 'body {background-color: red}';
  1. Use
let additionalCssStyle = document.getElementById('additionalCss');
if (! additionalCssStyle) {
  additionalCssStyle = document.createElement("style");
  additionalCssStyle.id = 'additionalCss';
  document.head.appendChild(additionalCssStyle);
}
additionalCssStyle.innerText = cssCode;
  1. To reload - save changed to backend, then repeat 1. and 2.
like image 6
Ventzy Kunev Avatar answered Oct 17 '22 16:10

Ventzy Kunev