Dynamic app style depending on URL parameter with Angular

Issue

I want to set different styles for my app, depending on a URL parameter (that I already got).

I tought to do something like this:

let dynamicCSS;

@Component({
    selector: 'app',
    templateUrl: './app.component.html',
    styleUrls: [require('./app.component.css'), require('./app.component.' + dynamicCSS + '.css')],
    encapsulation: ViewEncapsulation.None
})
export class App.........

But in this case, the "require" says: "Cannot be found", and I don’t know how to access my dynamicCSS variable from my ngOnInit().

How can I solve this?

Solution

I went back to work on this and figured out how to do what I needed. It was simpler than I imagined. All I had to do was create a function like this:

loadCSS() {
    let fileRef;
    fileRef = document.createElement('link');
    fileRef.setAttribute('rel', 'stylesheet');
    fileRef.setAttribute('type', 'text/css');
    fileRef.setAttribute('href', '../../assets/dynamicStyles/appointment2.component.css');
    if (typeof fileRef !== 'undefined') {
        document.getElementsByTagName('head')[0].appendChild(fileRef);
    }
}

This function injects a new CSS Style into the page, that way I can replace the entire style on the page.

NOTE 1 The file MUST be inside /assets.

NOTE 2 The file MUST be .css, cannot be .scss.

NOTE 3 No need to add the file path in "styles" inside angular.json, nor in @Component inside my app.component.ts.

Answered By – Liu

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published