Thibs Thibs - 5 months ago 130
AngularJS Question

Is it possible to dynamically change global stylesheets in Angular 2?

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?

Answer

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');
    }
}