0

In asp.net core, I can conditionally include css/js in my layout html page using <environment> tags:

<environment names="Development,Staging">
    <script type="text/javascript" href="js/debug.js"></script>
    <link rel="stylesheet" type="text/css" href="css/style.css" />
</environment>

<environment names="Production">
    <link rel="stylesheet" type="text/css" href="css/style.min.css" />
</environment>

How can I achieve this in angular 2? The css/js files that I'm talking about are site-wide, not component-specific

(PS. I'm new to angular 2)

2
  • stackoverflow.com/questions/36004810/… Commented May 29, 2017 at 5:01
  • @TheDictator I'm new to angular 2, I'm not sure I can do this since meta tags are outside the scope of traditional angular binding??? Commented May 31, 2017 at 13:34

1 Answer 1

6
+50

If you are using angular2 CLI then you could use enironment.ts. Properties specified in this file will be available throughout entire application.

You can create multiple environments like this-

enter image description here

In components import default environment file like this-

import { environment } from '../../environments/environment';

Import DOCUMENT from platform-browser like this-

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

Inject into component (e.g. main AppComponent),

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

Use environment condition and apply dynamic style-sheet like this-

if(environment.EnvName === 'prod') {
        this.document.getElementById('theme').setAttribute('href', 'prod.css');
}
else {
        this.document.getElementById('theme').setAttribute('href', 'dev.css');
}

Angular CLI takes care of which file to use for each environment during build process.

This is how you can specify environment at a time build-

ng build --env=prod

Hope this helps in your use case.

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

1 Comment

This is great but what if you have more environments and, by extension, different variables per environment. You will need to pre build each environment and deploy them all together, then switch between SourcePaths based on the environment?

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.