MdAshiff
MdAshiff

Reputation: 146

Dynamically add CSS stylesheet in runtime using angular and Ionic 2

I'm trying to develop a dual language app in Ionic2. The languages are English and Arabic. I have two CSS files one is english.css and the other one is arabic.css, when changing from English to Arabic, the english.css should be removed and arabic.css should be added at runtime. Are there any possibilities?

Upvotes: 0

Views: 470

Answers (1)

Riccardo Zorn
Riccardo Zorn

Reputation: 5615

I just faced the very same issue. Turns out this is not really the best way to achieve the result (loading and unloading the stylesheets will create an awkward effect as the page rerenders). Also you want to target rtl and ltr rather than the individual languages, or define a ltr-rtl variable based on the language in scss.

Rather, you should add a class to either your head or your body / pages / components that reflects the language, and have those (few I imagine) queries for rtl languages built upon said constants. I only needed it on a custom button-bar component, and it turned out to be as simple as this:

Liveservice (my global singleton service)

// this can be "rtl" or "ltr"
public rtlClass: string;

Component Markup

<top-button-bar>
<div [ngClass]="liveService.options.rtlClass">
<ion-button>this will be centered, always</ion-button>
<ion-segment>
<ion-segment-button>1</ion-segment-button>
<ion-segment-button>2</ion-segment-button>
<ion-segment-button>3</ion-segment-button>
</ion-segment>
</div>
</top-button-bar>

Now the purpose is to have the layout as such:

ltr: ___B123
rtl: 321B___

The scss style:

top-button-bar {
  .ltr {
     // scss code for ltr layout here
  }
  .rtl {
     // scss code for the rtl layout here
  }
}

Upvotes: 1

Related Questions