Is it possible to add a global CSS file to Angular 2? At the moment I have many different components that have the same button styling - but each of the components have their own CSS file with the styling. This is frustrating for changes.
I read somewhere on Stack Overflow to add:
import { ViewEncapsulation } from '@angular/core'; //add this @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'], encapsulation: ViewEncapsulation.None //add this })
So I added the ViewEncapsulation lines in the root component, then added the CSS styling to the root app CSS (app.component.css) and removed the CSS styling from individual component CSS files, and it did not work.
Surely there is a way to add a global CSS file? Do I need to add something to the individual components to make them access the global CSS file?
If you create your project using angular cli you will find a file styles. css under src folder.
What are global styles? When people talk about the global nature of CSS, they can mean one of a few different things. They may be referring to rules on the :root or <body> elements that are inherited globally (with just a few exceptions).
Just write your global styles in your src/styles.css
file. That file will be added to styles.bundle.js
when you run ng build
.
If you'd like to add more style files, you can do so in your .angular-cli.json
(or angular.json
for Angular 6+) file. In that file you'll see an array called styles
, with a single item by default which is styles.css
(or src/styles.css
in Angular 6). You can even include .scss
files.
If you want to use SCSS, simply change the extension of your src/styles.css
file to .scss
, then reflect the change in your .angular-cli.json
(or angular.json
in 6+) file as well, by editing the entry in the styles
array.
When creating components, you'd like Angular to create .scss
styles files instead of .css
. Here's how:
Starting from Angular 7, when you create an app with ng new appname
, you will be prompted which stylesheet format you'd like to use, so you just choose SCSS (source). It seems like here ends the need to manually configure Angular to use SCSS.
Add this at the end of your angular.json
file (source):
"schematics": { "@schematics/angular:component": { "styleext": "scss" } }
Locate this by the end of your .angular-cli.json
file, and change the value of styleExt
to scss
:
"defaults": { "styleExt": "css", "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