小编典典

是否可以在Angular 2中动态更改全局样式表?

angularjs

是否可以动态更改全局样式表?

编辑:目的是允许用户选择他喜欢的样式。

在Angular 1中,我能够将控制器包装在head标签周围并在其中使用绑定。

下面的示例(简化代码):

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

在Angular 2中有可能吗?


阅读 393

收藏
2020-07-04

共1个答案

小编典典

我最终使用了Igor在这里提到的DOCUMENT令牌。

从那里,我可以将href换成样式。

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