6

The below code is that define for style.

<!-- for mobile -->
<link rel="stylesheet" href="/dist/css/mobile.css">

<!-- for desktop -->    
<link rel="stylesheet" href="/dist/css/desktop.css">

I want to add above files to <head> in 'src/index.html' by condition.

How can I apply a css file for each device?

As you know, I can't use 'Conditional' code in 'index.html'.

Note that I will not use the method below.

// in angular-cli.json
"apps": [
    {
        "root": "src",
        "index": "index.html",
        "styles": [
            "/dist/css/mobile.css",
            "/dist/css/desktop.css"
        ]
    }
]


// in component.ts
@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrl: '/dist/css/mobile.css'
})

I look forward to your advice.

Thank you.

1 Answer 1

20

To dynamically load or change your CSS, you can do the following:

  1. In index.html:

    You will have a stylesheet link as follows:

    <link id="theme" href="assets/light.css" rel="stylesheet" >

    Note that there is "id" for the link element.

  2. In your component you will have as follows:

    Import the DOCUMENT from platform-browser

    import { DOCUMENT } from "@angular/platform-browser";

    then, in your action or on init you will change your css accordingly:

    this.document.getElementById('theme').setAttribute('href','assets/dark.css');

By default, you will load one CSS file.. lets say desktop.css. In your application's root component, you can look for the device or cookie or setup some conditions to change from desktop.css to mobile.css. Like you said, you will NOT use angular-cli.json to load your CSS.

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you so much!
@nasangW if the answer helped you why didnt you mark it as the right answer to really help others looking for same answer to know that this is the right anwser ?
document.getElementById('theme').setAttribute('href','assets/dark.css');
DOCUMENT now is imported from @angular/common. The above import statement is deprecated.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.