我是一个双语网站,每种语言都有自己的样式表,我想根据所选语言动态加载样式表
如何使用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,它包含当前语言,并在此组件中成功引用。
答案 0 :(得分:3)
您可以使用 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