Loading CSS files conditionally in Angular2's index.html

Currently, my index.html page features a dark theme:

<base href="/">
<html>
<head>
    <title>XXX</title>
</head>
<body>
    <link rel="stylesheet" type="text/css" href="assets/dark_room.css">
    <my-app>Loading...</my-app>
</body>
</html>

In addition to the dark theme, I have a bright "light_room.css" theme that users can switch to according to their preferences. How can I implement this feature?

My initial thought was to use a URL parameter, so if a user types ?light_room=True at the end of the URL, the light_room.css file would load. However, I realize this may not be possible in index.html as it is typically used for static content.

Has anyone encountered a similar situation and successfully conditionally loaded a CSS file in their index.html?

Answer №1

Theming is often just a matter of changing colors to give your app a different look. You can manage multiple themes within one CSS file by dynamically adding classes like my-app > .dark.

Let me show you an example of how I implement this:

app-theme.scss:

@import '~@angular/material/theming';

@include mat-core();
$words-app-primary: mat-palette($mat-teal, 300);
$words-app-secondary: mat-palette($mat-indigo, 500);
$words-app-warn: mat-palette($mat-red, 500);

$words-app-theme: mat-light-theme($words-app-primary, $words-app-secondary, $words-app-warn);
@include angular-material-theme($words-app-theme);

app-words-root > md-sidenav-container.dark {
  $words-app-theme-dark: mat-dark-theme($words-app-primary, $words-app-secondary, $words-app-warn);
  @include angular-material-theme($words-app-theme-dark);
}

app.component.html:

<md-sidenav-container [class.dark]="useDarkTheme"> ... </md-sidenav-container>

Non-Angular Version

app.component.js

import { DOCUMENT } from '@angular/platform-browser';

class AppComponent {
  constructor(@Inject(DOCUMENT) document: any) {
    let head = document.getElementsByTagName('head')[0];
    let link = document.createElement('link');
    link.rel = 'stylesheet';
    link.type = 'text/css';
    link.href = 'assets/dark_room.css'; // you may want to retrieve this from local storage or another location
    head.appendChild(link);
  }
}

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

PrimeFaces: Achieving Conditional Coloring Based on Status (Passed/Failed)

Attempting to dynamically change the color of a column based on its status value (Passed/Failed/InProgress) using jQuery. I tried copying and pasting the table into jsfiddle, where it worked. However, when implemented in the actual XHTML file, the jQuery ...

Retrieve data from a variable that is located within a function that is also

<script> const tally ={ total: 0, increase: function(){ total++; console.log(total); } } const selectBtn = document.getElementsByTagName('button& ...

Tips for customizing the color of pagination in bootstrap

I'm currently in the process of designing a website and I've chosen to implement Bootstrap's pagination for navigating between pages. Due to time constraints, I was wondering if anyone knows how I can utilize classes like "bg-dark", "bg-prim ...

I possess a list of unique identifiers and require the ability to either update an existing object within an array contained in a MongoDB document, if it exists,

I am facing a challenge in updating a specific element within an array in a MongoDB document. I have multiple IDs of that array and need to update the matching element using those IDs. data= [ { "planId" : "plan_FVNvrmjWT7fRDY", "startTime": ...

Is it possible to slide-toggle and alter the background color of a div when clicked?

Imagine having several div's on a webpage all with the ID of "Toggle". Each div contains two other smaller divs. "Headline" which is always visible. "Comment" which appears/disappears when the headline is clicked (initially hidden). How could I ac ...

Tips for distinguishing individual rows within a table that includes rowspans?

My Vue application calculates a table with rowspans by using an algorithm based on a configuration file. This allows the application to render columns (and maintain their order) dynamically, depending on the calculated result. For example, see the code sn ...

Tips for Establishing Communication Between Two Dynamic Canvas Elements

How do I establish communication between two animated canvas elements? I have created two HTML5 canvas animations using Adobe Animate CC. Both of these animations are placed on a single HTML page. I am able to call functions from within the animations and ...

Implementing a dynamic background change based on the current date in JavaScript

Is it possible to change the background of the body element based on the season using JavaScript? Here is a code snippet that demonstrates how to achieve this: // Function to determine the current season in the southern hemisphere // If no date is prov ...

Align the last column to the right side using HTML

I am facing an issue with my current project. I have a page that displays a list of posts in a CSS grid. The last two columns of the grid are supposed to be right-aligned, but for some reason, it's not working as expected. Here is the snippet of the c ...

The Jquery image on.load event seems to only function properly after performing a manual hard refresh of

Looking for a solution to replace loading text with a button only after the image has loaded onto the page. Utilizing on.load as follows: $('img.house').on('load', function() { $('.loading').hide(); $('# ...

jQuery mobile : accessibility helper for hidden elements

Within my HTML structure: <div data-role="fieldcontain" id="containdiv" class="no-field-separator"> <label for="field1" class="ui-hidden-accessible">To</label> <input type="search" name="field1" id="field1" autocorrect="off" a ...

When the HTML content matches a specific value, initiate a click event to trigger

Can anyone help me troubleshoot? I've tried multiple methods but can't seem to get it right. Here's a breakdown of what I'm attempting to accomplish: #info-NUMBER-btn shows Click to display more information. #info-NUMBER CSS is set t ...

Using v-bind:class in Vue.js does not successfully assign a value in the method

Why is the width of my div not changing when I try to bind it to a data attribute that ranges from 0 to 100? <div class="bar" :style="{ width: percentage + '%' }"></div> <script> export default { name: 'app&ap ...

Encountering a Vue syntax error following the binding of a session variable

Encountering a syntax error while attempting to bind a session variable as a prop of my Vue component. Scrutinizing my code did not reveal any mistakes, but perhaps another set of eyes may catch something. This is where I have registered my components: V ...

Is it feasible to develop a Grafana datasource plugin that does not rely on an external backend system?

I am in the process of developing a Grafana datasource plugin that operates independently without relying on an external backend. My plugin is based on the simple-json datasource plugin available at: https://github.com/grafana/simple-json-datasource In a ...

Is there only a single particle in Three.js?

I am trying to add a single particle to my scene and have the ability to move it around. However, my attempts to do so without using a Particle System have been unsuccessful. Whenever I try to render the particle as a mesh, nothing appears on the screen. I ...

Concerns about unchanging Behavior Subject affecting Ionic 4 interface

I have created a list program using Ionic 4 and attempted to update the list by utilizing BehaviorSubject from rxjs. The list updates properly when initialized in the ngOnInit() method, but fails to update within the add() callback. Despite logging the ou ...

Using Typescript to create an asynchronous function without explicitly declaring a Promise

When you examine TypeScript's async function, you may notice the redundancy with "async" and "Promise<type>". public async test(): Promise<string> { return "Test"; } Is there a way to configure TypeScript to handle async types ...

What is the best method for storing and accessing audio files that users upload in my MERN application?

I am developing a MERN application and am looking to implement a feature that allows users to upload audio files. I have read that storing the files directly in the database or within a folder inside the app is not recommended. I need a solution that en ...

Unable to retrieve DOM value due to Vue.js template being inaccessible in Chromium, including from both DevTools and extensions

Currently, I’m developing a Chrome extension that needs to retrieve specific values from a webpage such as the item title. However, instead of fetching the actual title, it is reading a Vue.js template variable. Even when I use DevTools to inspect the p ...