2016-06-09 41 views
5

是否可以動態更改全局樣式表?是否可以動態更改Angular 2中的全局樣式表?

編輯:其目的是讓用戶選擇他喜歡的風格。

在Angular 1中,我能夠在頭標上包裹控制器並在其中使用綁定。下面

實施例(簡化代碼):

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

這是可能在角2?

+0

你試過了嗎?發生了什麼? – Jamiec

+0

你想通過動態改變鏈接標籤來完成什麼?可能有不同的方式來實現相同的功能。 :) – Harangue

回答

6

我結束了使用DOCUMENT令牌,因爲伊戈爾提到here

從那裏,我能夠交換樣式的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'); 
    } 
} 
3

不,您不能在Angular應用程序之外使用任何綁定。角度應用程序只能在<body>之內或之內。因此沒有辦法使這項工作。

您可能會看看Title service的實現方式,以瞭解如何訪問<head>中的元素或僅使用普通的JS/TS對其進行必要的修改。

0

試試這個:在你的根組件模板中包含一個可變樣式錶鏈接。

@Component({ 
    selector: 'app', 
    template: ` 
    <link rel="stylesheet" href="styles/{{ current }}"> 
    ...` 
}) 
export class AppComponent { 
    current = 'site1.css'; 
} 
相關問題