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:
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.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?
using CSS3 variables, I have enough control over the parameters that i want to offer. The resulting structure is as follows:
mylib
ng-package.json
scss
mytheme.scss
src
public-api.ts
lib
my.component.ts <- standalone component
my.component.scss
ng-package.json:
{
"$schema": "../../../node_modules/ng-packagr/ng-package.schema.json",
"dest": "../../../dist/mylib",
"lib": {
"entryFile": "src/public-api.ts",
"styleIncludePaths": [
"scss"
]
},
"assets": [
"scss/*"
]
}
theme.scss:
:root {
--some-size-variable: 3px;
--some-color-variable: #22aaff;
}
public-api.ts:
export * from './lib/my.component';
my.component.ts:
@Component({
standalone: true,
template: '',
styleUrls: ['my.component.scss'],
})
export class MyComponent {
// lots of Angular goodness
}
my.component.scss:
@import 'mytheme'; // <-- this import is possible without relative path due
// to the "styleIncludePaths" in ng-package.json.
:host {
border-radius: var(--some-size-variable);
color: var(--some-color-variable);
}
Then, in the consuming application, the variables can be overwritten in a global scss file:
@import '~mylib/scss/mytheme';
$main-color-of-consuming-application: #ff0000;
:root {
--some-size-variable: 4px;
--some-color-variable: #{$main-color-of-consuming-application};
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With