是否可以在Angular 2中动态更改全局样式表? [英] Is it possible to dynamically change global stylesheets in Angular 2?
本文介绍了是否可以在Angular 2中动态更改全局样式表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以动态更改全局样式表?
Is it possible to dynamically change global stylesheets?
目的是允许用户选择自己喜欢的样式.
The purpose is to allow the user to pick the styles he prefers.
在Angular 1中,我能够将控制器包装在head标签周围并在其中使用绑定.
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
index.html
<!DOCTYPE html>
<html ng-app="app" ng-controller="AppController">
<head>
<title>Title</title>
<link rel="stylesheet" ng-href="styles/{{current}}"/>
</head>
...
AppController
AppController
app.controller('AppController', ['$scope', function ($scope ) {
$scope.current = dynamicValue;
}]);
在Angular 2中有可能吗?
Is this possible in Angular 2?
推荐答案
I ended up using the DOCUMENT token as Igor mentioned here.
从那里,我可以将href换成样式.
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');
}
}
这篇关于是否可以在Angular 2中动态更改全局样式表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文