Angular2 - 更改index.html的全局样式,或将styleurl应用于路径

时间:2016-09-01 18:37:47

标签: angular

我使用bootswatch中的样式,(CSS文件替换bootstrap的CSS文件),我想在我的应用程序的每个路径上使用不同的一个(例如控制面板) 意味着我需要在激活特定路由时全局应用不同的CSS文件 我尝试从index.html中删除CSS链接并将其放在主要组件的StyleUrls中,就像这样(我的网站的一个分支的虚拟示例):

import { Component } from '@angular/core'
import { ROUTER_DIRECTIVES, Router } from '@angular/router'

@Component({
    moduleId: module.id,
    styleUrls: ['../../../assets/css/bootstrap-simplex.css'],
    template: '<navbar></navbar><router-outlet></router-outlet>' ,
    directives: [ROUTER_DIRECTIVES]
})
export class AdministrationComponent {
    constructor(public router: Router){}

}

现在这确实会改变此组件元素的样式,但不会改变其router-outlet

内的子元素或组件的样式

那么有没有办法让styleUrls继承到子组件?或者我可以以编程方式更改index.html的CSS链接吗?

谢谢。

1 个答案:

答案 0 :(得分:0)

嗯,解决方案是@GünterZöchbauer建议的(谢谢)
是在index.html中创建一个js函数,然后从组件中调用它,如下所示:

的index.html

<link id="globalTheme" href="libs/bootstrap.min.css" rel="stylesheet">
<script>
    var file;
    function changeTheme(section) {
        switch (section) {
            case 'primary':
                file = '-flatly';
                break;
            case 'administration':
                file = '-lumen';
                break;
        }
        document.getElementById("globalTheme").setAttribute("href",'libs/bootstrap' + file + '.min.css');
    }
</script>

然后在组件中

import { Component } from '@angular/core'
import { ROUTER_DIRECTIVES, Router } from '@angular/router'

declare var changeTheme: any

@Component({
    moduleId: module.id,
    templateUrl: '../templates/administration.template.html',
    directives: [ROUTER_DIRECTIVES]
})
export class AdministrationComponent{
    constructor(public router: Router){
        changeTheme('administration')
    }

}

希望这对某人有用。