Maybe a global service would help~
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);
}
}
}
Now , provider RtlService in AppModule ,and in other component when you want to change the direction just inject RtlService and call the setMode method.