Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 990
Thibs Avatar asked Jun 09 '16 15:06

Thibs


3 Answers

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');
    }
}
like image 130
Thibs Avatar answered Oct 20 '22 04:10

Thibs


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.

like image 38
Günter Zöchbauer Avatar answered Oct 20 '22 06:10

Günter Zöchbauer


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';
}
like image 1
CurlyFro Avatar answered Oct 20 '22 06:10

CurlyFro