【问题标题】:Conditionally loading stylesheet Angular 2有条件地加载样式表Angular 2
【发布时间】:2017-05-22 18:13:42
【问题描述】:

我有一个双语网站,每种语言都有自己的样式表,我想根据所选语言动态加载样式表

知道如何使用 Angular2 来实现这样的要求吗?

这里是组件装饰器

@Component({

selector: 'recent-recognition',
template: require('./recent.recognition.component.html'),
styles:
[
    //I want to load only one of these based on if condition
    require('./recent.recognition.component.css'),
    require('./recent.recognition.component.ar.css')
]
})

我也有 translate.service ,它包含当前语言并在此组件中成功引用。

【问题讨论】:

    标签: angular localization components stylesheet


    【解决方案1】:

    你可以像这样使用DOCUMENT来切换主题-

        import { Component, Inject } from '@angular/core';
        import { DOCUMENT } from '@angular/platform-browser';
    
        @Component({
                selector: 'app-root',
                template: `
                  <label class="switch">
                    <input type="checkbox" [checked]="theme" (change)="toggleTheme($event)">
                    <div class="slider round"></div>
                  </label>
                `,
        })
    
        export class SomeComponent {
    
        constructor (@Inject(DOCUMENT) private document) { }
    
        toggleTheme(e: any) {
        this.theme = !this.theme;
    
        if(this.theme) {
                this.document.getElementById('theme').setAttribute('href', 'condition1.css');
        }
        else {
                this.document.getElementById('theme').setAttribute('href', 'condition2.css');
        }
    
        }
    }
    

    参考:https://angular.io/docs/ts/latest/api/platform-browser/index/DOCUMENT-let.html

    【讨论】:

    • if 语句应该在ngOnInit 中吗?
    • 我不明白,你设置了什么样的标签的href?什么是主题元素?
    猜你喜欢
    • 2017-07-18
    • 1970-01-01
    • 1970-01-01
    • 2017-10-04
    • 2017-08-01
    • 2014-05-01
    • 2017-02-02
    • 1970-01-01
    • 2016-09-26
    相关资源
    最近更新 更多