0

I would like to use bootstrap with angular4 , I need also to support RTL styling, in bootstrap there is no yet official support. There are several github projects providing patches. In the old days I used jquery to change the styles on the fly when someone selects RTL language. How I should do the same in angular 4. IN general , I need a component which responsible for changing the html dir properties based on style as well as changing the css styles.

Since I an new to the technology, how this can be done. What are the proper patches, a js fiddle example would be great.

Thanks in advance

Mohamed Gara
  • 2,665
  • 3
  • 13
  • 19

1 Answers1

0

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.