N0rA
N0rA

Reputation: 612

Conditionally loading stylesheet Angular 2

I've a bilingual website en and ar each language have its own stylesheet and I'd like to dynamically load the stylesheet based on the selected language

any idea of how to implement such a requirement by using Angular2?

here is the component decorator

@Component({

selector: 'recent-recognition',
template: require('./recent.recognition.component.html'),
styles:
[
    //I want to load only one of these based on if condition
    require('./recent.recognition.component.css'),
    require('./recent.recognition.component.ar.css')
]
})

I also have translate.service which contains current language and is referenced in this component successfully.

Upvotes: 4

Views: 2767

Answers (1)

Sanket
Sanket

Reputation: 20027

You could use DOCUMENT to switch theme like this-

    import { Component, Inject } from '@angular/core';
    import { DOCUMENT } from '@angular/platform-browser';

    @Component({
            selector: 'app-root',
            template: `
              <label class="switch">
                <input type="checkbox" [checked]="theme" (change)="toggleTheme($event)">
                <div class="slider round"></div>
              </label>
            `,
    })

    export class SomeComponent {

    constructor (@Inject(DOCUMENT) private document) { }

    toggleTheme(e: any) {
    this.theme = !this.theme;

    if(this.theme) {
            this.document.getElementById('theme').setAttribute('href', 'condition1.css');
    }
    else {
            this.document.getElementById('theme').setAttribute('href', 'condition2.css');
    }

    }
}

Reference: https://angular.io/docs/ts/latest/api/platform-browser/index/DOCUMENT-let.html

Upvotes: 5

Related Questions