0

I have this function to load stylesheet based on user's choice 'en' or 'ar':

addStyleSheet(lang: string) {
        let headID = document.getElementsByTagName('head')[0];
        let link = document.createElement('link');
        link.type = 'text/css';
        link.rel = 'stylesheet';
        link.id = 'widget_styles';link.type = 'text/css';


        headID.appendChild(link);
        if (lang == "ar") {
            link.href = AppGlobals.APP_URL + './assets/css/bootstrap-rtl.css';
        }
        else if (lang == "en") {
            link.href = AppGlobals.APP_URL + './assets/css/bootstrap.css';
        }
    }

My default language is English so the first page is working fine, also the first 'ar' choice fine and success to load 'bootstrap-rtl', but when I press 'en' again, the 'bootstrap-rtl' is already loaded so the design crash, I tried to unlink the css file using removeChild but it doesn't work fine, any ideas?

Marvin Ericson
  • 239
  • 2
  • 7
  • 20

1 Answers1

0

Disable the CSS element on function call

constructor(private myElement: ElementRef, @Inject(DOCUMENT) private document) {

}
addStyleSheet() {
        this.document.getElementById('eng-css').disabled = false;
        this.document.getElementById('otherlang-css').disabled = true;
    }

<link rel="stylesheet" id="eng-css" type="text/css" href="css/start.min.css" />
<link rel="stylesheet" id="otherlang-css" type="text/css" href="css/app.min.css" />

Phani Kumar
  • 171
  • 7
  • I got this error ERROR TypeError: Cannot set property 'disabled' of null. I'm sure that the id is exist – Marvin Ericson Dec 13 '17 at 13:25
  • what about "this.document" ? be sure to inject document into your constructor of Component https://stackoverflow.com/questions/37521298/how-to-inject-document-in-angular-2-service – Phani Kumar Dec 14 '17 at 14:03
  • import { Inject } from '@angular/core'; import { DOCUMENT } from '@angular/platform-browser'; @Component({ templateUrl: ' ' }) export class YourComponent{ constructor(@Inject(DOCUMENT) private document) {} } – Phani Kumar Dec 14 '17 at 14:07