Thibs Thibs - 4 months ago 70x
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):


<!DOCTYPE html>
<html ng-app="app" ng-controller="AppController">
<link rel="stylesheet" ng-href="styles/{{current}}"/>


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.


   <link id="theme" rel="stylesheet" href="red.css">


import { Component, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/platform-browser';

export class MyClass {
    constructor (@Inject(DOCUMENT) private document) { }

    ngOnInit() {
      this.document.getElementById('theme').setAttribute('href', 'blue.css');