Is it possible to dynamically change global stylesheets?
EDIT: The purpose is to allow the user to pick the styles he prefers.
In Angular 1, I was able to wrap a controller around the head tag and use bindings in there.
Example below (simplified code):
index.html
<!DOCTYPE html>
<html ng-app="app" ng-controller="AppController">
<head>
<title>Title</title>
<link rel="stylesheet" ng-href="styles/{{current}}"/>
</head>
...
AppController
app.controller('AppController', ['$scope', function ($scope ) {
$scope.current = dynamicValue;
}]);
Is this possible in Angular 2?
I ended up using the DOCUMENT token as Igor mentioned here.
From there, I was able to swap the href for the style.
HTML:
<head>
<link id="theme" rel="stylesheet" href="red.css">
</head>
TS:
import { Component, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/platform-browser';
@Component({})
export class MyClass {
constructor (@Inject(DOCUMENT) private document) { }
ngOnInit() {
this.document.getElementById('theme').setAttribute('href', 'blue.css');
}
}
No, you can't use any bindings outside Angular applications. Angular applications can only be at or inside <body>
. Therefore no way to make this work.
You might have a look at the implementation of the Title
service for how to access elements in <head>
or use just plain JS/TS to modify it imperatively.
try this: in your root component template include a variabled stylesheet link.
@Component({
selector: 'app',
template: `
<link rel="stylesheet" href="styles/{{ current }}">
...`
})
export class AppComponent {
current = 'site1.css';
}
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