Dynamically load different css files in angular2 application based on user's language

后端 未结 4 635
傲寒
傲寒 2021-01-11 18:42

I have an Angular2 application and it need to support multiple languages. Some of these languages may be RTL (i.e Persian) and some will be LTR (i.e. English). Apart from lo

4条回答
  •  旧时难觅i
    2021-01-11 19:23

    You'd need to conditionally add or remove the style from the browser:

    to add

    loadIfNot(url,cssId){
    
         if (!document.getElementById(cssId)){
            var head  = document.getElementsByTagName('head')[0];
            var link  = document.createElement('link');
            link.id   = cssId;
            link.rel  = 'stylesheet';
            link.type = 'text/css';
            link.href = url;
            link.media = 'all';
            head.appendChild(link);
        }else{
            document.getElementById(cssId).disabled = false;///i fit's already there, enable it
        }
    
      }
    

    and for remove

     disable(cssId){
         document.getElementById(cssId).disabled = true
     }
    

    Disable and Enable is because browser tends to cache your styles, and in order to make them enable or disable, you'd change that attribute

提交回复
热议问题