Liu
Liu

Reputation: 66

Dynamic app style depending on URL parameter with Angular

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?

Upvotes: 0

Views: 1564

Answers (2)

Liu
Liu

Reputation: 66

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.

Upvotes: 0

Wolfyr
Wolfyr

Reputation: 479

You do not have to include the require(). This should do the trick

styleUrls: ['./app.component.css', './app.component.' + dynamicCSS + '.css']

Or to make it even cleaner:

styleUrls: ['./app.component.css', `./app.component.${dynamicCSS }.css`]

Make sure to add the dynamicCSS as a variable in the component file, but outside the component itself like in the example below (not a real world exaple since these 2 urls return the same file)

enter image description here

Upvotes: 1

Related Questions