Home > other >  Expose and use customizable variables in Angular library
Expose and use customizable variables in Angular library

Time:09-22

I have made an Angular library containing one component myComponent. I can successfully build it and use it in my main application. I want to add the functionality of customizing some of the scss variables that are used in myComponent by the consuming main application. I could not find any exhaustive guides on this topic. What I have so far:

  • In my lib, i have a theme.scss file that contains the variables that i want to be customizable. It is properly exported along with the lib by setting the assets value of the ng-package.json file.
  • myComponent uses the variables defined in theme.scss.
  • however, when i build the lib, the resulting files in dist no longer have the relationship to the theme.scss file, as the scss code is compiled by ng build. Therefore, changing the variables in the consuming app does nothing to myComponent.

Is it possible to get the desired behavior?

CodePudding user response:

You can turn off view encapsulation in your component. That way the styles applied are going to act as a global css file, that is probably the reason why the relationship to the theme file is not being kept

Alternatively you can pass the variables you need in an input to the component, which has the bonus of being explicit in the syntax when you use the component

CodePudding user response:

What I have done in my library for things like this, is adding a provider component. This is a component that you can put at the top of your application, and by adding inputs to it (maybe from a local libVars.js or something) you can set the variables in the ngOnInit of the provider.

// provider.component
const root: any = document.querySelector(':root');
root.style.setProperty(`--primary-color`, this.myColorVar);
// app.component.html
<provider myColorVar="red">
  // app contents
</provider>

Additionally, if you use SCSS, you can assign this dynamically set variable to an SCSS variable like

// style.scss
$myVar: --my-var;
  • Related