Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 - How to conditionally load css file in index.html?

What I have right now is a page with dark theme in index.html:

<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>

I also have a bright "light_room.css" theme that is required to implement, and user could switch theme base on needs. I am wondering how could I achieve this?

I thought it could be done by having an url parameter so that when user type like ?light_room=True at the end of url, the page will load light_room.css. However I think it can only be done in normal templates but not in index.html.

Does anyone have similar experience in conditionally loading css file in index.html?

like image 660
PIZZA PIZZA Avatar asked Oct 29 '22 07:10

PIZZA PIZZA


1 Answers

The point is that theming is usually just some different colors. You can add all themes to one css. my-app > .dark gets different colors and the class will be added dynamically in the code.

Here is a more detailed example how I use it:

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 get this from local storage or location
    head.appendChild(link);
  }
}
like image 75
iRaS Avatar answered Nov 11 '22 11:11

iRaS