To properly override variables of an Angular library, you can leverage Angular's style encapsulation mechanism and CSS variable scoping. This will allow you to modify the library's styles without directly modifying its source code. Here's a step-by-step guide on how to do it:

  1. Create a Styles File: In your Angular project, create a new styles file (e.g., library-overrides.scss or library-overrides.css) where you will define the variables you want to override. This file should be at the root level of your project or within your assets folder.

  2. Identify the Variables: Identify the CSS variables or SASS/SCSS variables used by the Angular library that you want to override. These variables should be listed in the library's documentation or source code. For example, if the library uses CSS custom properties (variables), they will be prefixed with --.

  3. **Use ::ng-deep or ::ng-host: In your library-overrides.scss file, you can use the ::ng-deep or ::ng-host selector to target the components of the Angular library and override their styles. For example, to override a variable named --primary-color, you can do the following:

::ng-deep { /* or ::ng-host for Angular 11+ */ .library-class { --primary-color: red; /* Your custom value */ } }

Here, .library-class should be replaced with the appropriate selector for the component you want to target in the Angular library.

  1. Import the Styles File: In your angular.json file, add the path to your library-overrides.scss file in the styles section. This will include your custom styles and variable overrides when your Angular application is built.
"styles": [ "src/styles.css", // or your main styles file "src/library-overrides.scss" ],
  1. Ensure Proper Encapsulation: When using ::ng-deep or ::ng-host, you might encounter style encapsulation issues depending on your Angular version and the view encapsulation strategy used by the library. If the styles are not applied correctly, try different view encapsulation strategies in your application (e.g., None, Emulated, or ShadowDom) to see which works best with the library you are using.

  2. Check for Updates: Be mindful of library updates, as the library's styles or variable names may change in newer versions. Always refer to the library's documentation and release notes for any changes related to customizing styles.

By following these steps, you can override the variables of an Angular library without directly modifying its source code. This approach allows you to keep your changes separate from the library codebase, making it easier to update the library and maintain your customizations.

Have questions or queries?
Get in Touch