I'm trying to create a function that changes the whole page css, injecting a new styleSheet.
I have the following function:
loadCSS() {
let fileRef;
fileRef = document.createElement('link');
fileRef.setAttribute('rel', 'stylesheet');
fileRef.setAttribute('type', 'text/css');
fileRef.setAttribute('href', './appointment2.component.scss');
if (typeof fileRef !== 'undefined') {
document.getElementsByTagName('head')[0].appendChild(fileRef);
}
}
Once user click on this function, the new css style should be applied. But it does not happen.
I'm getting the following error: Refused to apply style from 'http://localhost:4200/appointment2.component.scss' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
I've already added the path to my @Component styleUrls:
styleUrls: [
'./appointment2.component.scss',
'./appointment.component.scss'],
I've even already added it to my styles at angular.json:
"styles": [
"src/app/appointment/appointment2.component.scss",
"./node_modules/@angular/material/prebuilt-themes/indigo-pink.css",
"src/styles.scss",
"src/theme.scss",
"node_modules/ngx-toastr/toastr.css"
]
What am I doing wrong? How to fix this?
SASS (.scss) files are not valid CSS files.
They need to be transpiled into CSS first.
This means you can't use them in directly in your application.
Try providing a CSS (.css) file instead.
With the great help of @temp_user I discovered the file needed to be a '.CSS' file, and not '.SCSS'. But I was still getting one problem: The file could not be found (404 error at payload). So what I needed to do (besides changing the file format) was Move the file to /assets directory, and after this. Everything worked fine.
So, my code ended like this:
loadCSS() {
let fileRef;
fileRef = document.createElement('link');
fileRef.setAttribute('rel', 'stylesheet');
fileRef.setAttribute('type', 'text/css');
fileRef.setAttribute('href', '../../assets/dynamicStyles/appointment2.component.css');
if (typeof fileRef !== 'undefined') {
document.getElementsByTagName('head')[0].appendChild(fileRef);
}
}
With this code, I'm able to change my page full style, anytime I need.
NOTE It is not necessary to add the file path in "styles" inside angular.json, nor in @Component inside my app.component.ts