【问题标题】:angular 4 global style changeangular 4 全局样式更改
【发布时间】:2018-03-01 20:02:02
【问题描述】:
我想使用带有 angular4 的 bootstrap,我还需要支持 RTL 样式,在 bootstrap 中还没有官方支持。有几个提供补丁的 github 项目。在过去,当有人选择 RTL 语言时,我使用 jquery 即时更改样式。我应该如何在 Angular 4 中做同样的事情。一般来说,我需要一个组件来负责根据样式更改 html 目录属性以及更改 css 样式。
由于我是这项技术的新手,如何做到这一点。什么是正确的补丁,一个 js fiddle 例子会很棒。
提前致谢
【问题讨论】:
标签:
twitter-bootstrap
angular
【解决方案1】:
也许全球服务会有所帮助~
rtl.service.ts
import { Inject, Injectable,Output } from '@angular/core';
import { DOCUMENT } from '@angular/platform-browser';
@Injectable()
export class RtlService {
mode: 'normal' | 'rtl' = 'ltr';
constructor(@Inject(DOCUMENT) private document: any) {}
@Output() modeChanged = new EventEmitter();
insertCss(path) {
const head = this.document.getElementsByTagName('head')[0];
let link = this.document.createElement('link');
link.href = path;
link.rel = 'stylesheet';
link.type = 'text/css';
head.appendChild(link);
}
removeCss(path) {
const allStyles=this.document.getElementsByTagName('link');
for (var i=allStyles.length; i>=0; i--){
if (allStyles[i] &&
allStyles[i].getAttribute('href')!=null &&
allStyles[i].getAttribute('href').indexOf(path)!=-1) {
allStyles[i].parentNode.removeChild(allStyles[i]);
}
}
setDir() {
const htmlElement = this.document.getElementsByTagName('html')[0];
htmlElement.setAttribute('dir', this.mode);
}
setMode(newMode) {
if ( newMode === 'rtl' && newMode !== this.mode ) {
// insert css file
this.insertCss('assets/rtl.css');
this.mode = newMode;
this.setDir();
this.modeChanged.emit(this.mode);
} else (newMode === 'ltr' && newMode !== this.mode) {
this.removeCss('assets/rtl.css');
this.mode = newMode;
this.setDir();
this.modeChanged.emit(this.mode);
}
}
}
现在,AppModule 中的 provider RtlService 和其他组件中,当你想改变方向时,只需注入 RtlService 并调用 setMode 方法。