Avoid the hassle of repeatedly importing global SCSS variables for Angular components

I have defined SCSS variables in the file

src/styles/settings/_variables.scss
and imported them into src/styles.scss. However, these variables are not available for every component.

Is there a way to create a global file that contains all SCSS variables for all my components? It is cumbersome to include @import in every component's .scss file, especially with nested components.

I know there are similar questions, but they seem outdated and do not apply to the latest versions of Angular.

I am using Angular 7.3 with CLI.

Answer №1

To enhance your configuration, consider enclosing your global variable declarations within the :root{} selector in the

src/styles/settings/_variables.scss
file.

:root {
  --blue: #00b; // or any other global variables you want to share with components 
}

When using these variables in SCSS, make sure to reference them like this:

.example-class {
  background-color: var(--blue)
}

In addition, this technique can extend beyond colors and fonts to include mixins, media queries, keyframes, and more. The possibilities are not limited to just styling attributes.

To further organize your styles, create a global file at src/assets/style/global and import each individual scss file into it as needed.

@import 'filename';

If you wish to prevent certain components from accessing global variables once they are implemented, explore how ViewEncapsulation in Angular can help isolate these styles.

Answer №2

Is there a way to have global access to scss variables in all components?

Unfortunately, it is not possible to automatically have access to the sass variables without importing the global file in each component.

In SASS, when using partials to organize code better, you can use the @import directive to reference shared variables. For example, if you have sass variables in a file called shared/_variables.scss:

$lightslategray: #778899;
$darkgray: #A9A9A9;

If you want to use these variables in another stylesheet, you need to import the stylesheet that contains them first:

// Shared
@import "shared/variables";

.content {
  background: $lightslategray;
}

In Angular, referencing external stylesheets works similarly. If you need to use some

sass variables, mixins, or functions
in a specific component.scss, you must use the @import directive to reference them in that file. To simplify this process, you can create a file named src/_variables.scss and use syntax like this in your component.scss:

@import “~variables.scss”;

Answer №3

Accessing sass styles globally is a breeze with just two simple steps.

  1. Add the folder path of your style files to the includePaths array in the angular.json file.
  2. Import specific style files by their filenames in any component as needed.

For example, if your file and folder structures look like this: src > my-styles-folder > var.scss

angular.json

"architect": {
  "build": {
    ...
    "options": {
      "stylePreprocessorOptions": {
        "includePaths": [
          "src/my-styles-folder" // Just add the path without the file name
        ]
      },
      "styles": [
        ...
      ]
    }
    ...
  }
}

var.scss

$toolbar-heigh: 70px;

some-component.scss

@import "var"; // Import var.scss

mat-toolbar {
  height: $toolbar-height;
}

Answer №4

First, navigate to the custom SCSS file located at shared/css/_variable.scss and add the following:

:root{
  --color-text: red;
  --color-btn-success: green;
}

Next, open the style.scss (main file) and import the variables file:

@import './shared/css/Variables';

You can now utilize these variables in all components using this syntax:

.sample{
  color : var(--color-text);
}

Answer №5

When using angular 8, this solution worked well for me.

To customize your styles in Angular, you need to modify the _variable.scss file as follows:

:root{--my-var:#fabada}

Next, navigate to your angular.json file and update the "styles" section with the following line:

{"input":"yourPath/_variables.scss"}

Answer №6

A quick way to streamline your stylesheets is by utilizing the :root{--my-var:#fabada} declaration in your styles.scss/css instead of relying on an additional _variables file. This allows you to simply reference var(--my-var) within any component.

Answer №7

After much experimentation, I discovered that the most effective method to accomplish this task is by translating scss variables into css custom properties.

Within the _variables.scss file, all scss variables are stored:

$purple: hsl(270, 60%, 50%);

Subsequently, I transform them into standard css variables:

:root {
    --purple: #{$purple};
}

Answer №8

Utilize variables from external files within each angular component:

@use "/src/styles/settings/variables" as *;

Once you import your variables, they will be accessible in your component. I trust this information proves helpful to you.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Implementing a persistent "remember me" feature in Angular 2 without relying on local

Is it possible to implement a "remember me" feature in Angular 2 without relying on the use of local storage? ...

The rendering of a variable in ngAfterViewInit() is displaying unexpected behavior

Have there been any recent changes to variables in ngAfterViewInit()? You can find the stackblitz app here Component File import {ChangeDetectionStrategy,ViewChild,AfterViewInit,Component,ChangeDetectorRef} from '@angular/core'; import {CdkVir ...

Is this file malicious?

Greetings and thank you for taking the time to read my inquiry. I have come across a peculiar JavaScript file that is being loaded on my website. It appears to reference Typekit, however, this particular file is not present on my testing site and has an u ...

How to convert JSON data (excluding headers) into a string array using TypeScript

I am attempting to extract the raw data from the JSON without including the headers. For example, I want to retrieve '1' but not 'ID', or 'foo' but not 'Name'. [{ID = 1, Name = "foo", Email = "<a href="/cdn-cgi/l ...

JavaScript Karma Automatic Tests Failing and Angular Generated

I'm struggling to comprehend the behavior of the automatically generated .spec.ts tests in Angular. Each test contains expect(component).toBeTruthy();, which should be a straightforward check to verify if the component was created successfully. Howeve ...

Access denied: Authentication with Google Sign-In in Firebase is not permitted for this domain

I'm encountering difficulties with enabling Firebase Google sign-in for a custom domain. Strangely enough, it seems to work perfectly fine when the app is running on localhost. I have already added the custom domain to the list of Authorized domains w ...

The slideout tab must remain fixed to the left side of the div on smaller screens, regardless of any other factors

I am currently creating a SlideOut filter div. By default, this Div is positioned on the right side of larger screens. However, when the screen size decreases, the Sidebar disappears and the .SlideOutTab becomes visible. Between 768px and 992px, both the ...

"Reorganizing React components with CSS Grid: A Step-by-Step Guide

|----------| | Form | |----------| //current layout | Bookings | |----------| |----------| | Bookings | |----------| //desired layout | Form | |----------| Is there a way to adjust the order of components in the <main> container so that ...

Avoiding Redundant HTTP Requests in Angular 2 Template Iterations

In my template, I am using an ngFor to iterate through data received from an asynchronous observable: <div *ngFor="let result of data.results"> <div> <img [src]="parseSrc(result.src)" alt="{{ getCaption(result.id) | async }}" /> ...

"Adjust the orientation of a video and ensure it properly fills the screen with CSS styling

Below is the CSS style being used: video { position: absolute; transform: rotate(90deg); width: 100%; height: 100%; z-index: 4; visibility: visible; } This code snippet demonstrates a video element: <video id="myVideo" ...

Expanding section beneath a Row in a Table (Semantic UI React)

I'm attempting to implement expandable Table Rows in a Table that can be activated by clicking on them individually. For instance, upon clicking on the designated area in the provided image below, a Segment or Container will reveal itself with embedd ...

The CSS file I've linked to in my HTML (ejs) document seems to be getting

As I work on developing my app from the backend, I am encountering an issue with loading CSS locally on my page. I am utilizing Node.js, Express.js, and EJS for my pages - part of the MEN/MEAN stack. <link href="../public/stylesheets/style.css" rel="st ...

The height of a table cell in MVC cannot be altered

Could someone please help me with changing the height of table cells in MVC using Dreamweaver? I have already created the table with the following structure, but I am struggling to adjust the cell height. Any advice or tutorials would be greatly appreciate ...

Tips for transferring a column in an array to an object field within an array

I have a piece of code where I need to pass values from the 'dataList' array into this.data object's 'labels' and 'datasets'-> data. When I try to directly set the values, I get an undefined result. So I created a var ...

Tips on Showing a Unique List in Mat-Table?

Here's what I'm trying to accomplish: I have a list and I want to display it without any duplicates. I attempted using the code (this.model.map(x => x.map), but it resulted in an error. Can anyone help me fix this? model: myModel[]; myObj:any; ...

What are the steps for transitioning with JavaScript?

My goal is to make both the <hr> elements transition, but I'm struggling with only being able to select the lower <hr> using CSS. html { margin-bottom: 0; height: 100%; min-height: 100%; } body { margin-top: 0; height: 100%; ...

Angular application in a subdirectory experiencing a looped redirection issue

I am currently in the process of setting up an Angular application to be hosted from a subdirectory of an existing website. The main website is located at https://localhost/abc, while the Angular app is being served at http://localhost:4200 using ng serve. ...

Encountered compilation errors while trying to compile the entry-point @ng-bootstrap/ng-bootstrap with `es2015` as esm2015. Compilation was unsuccessful

Seeking assistance in resolving the errors provided below. I am currently in the process of upgrading my angular project from version 8 to 12. Initially, I attempted to upgrade progressively from version to version, starting with "7 to 8, 8 to 9". However ...

Craft an engaging and dynamic Image map with SVG technology to elevate responsiveness and interactivity

I'm currently working on a website and I need to create two clickable sections on the home page. Each section will lead to a different specialization of the company. To achieve this, I decided to use a square image split into two right-angled triangle ...

"Utilizing ngx-formly datetime picker in Angular 8 for efficient date

I am attempting to create a datetimepicker using the ngx-formly library. Despite reviewing all the examples in the official documentation, offical docs, I am still unsure how to implement it. Can anyone recommend a custom form field or provide guidance o ...