Display Current Environment in Angular App

March 31, 2021 • • Published By • 2 minute read

Have you ever wanted to display which environment your user was in somewhere in your Angular application? Maybe display a Beta label in the header of the app if they are currently using the Beta environment? Let’s learn how!

Table of Contents

Environments

By default, Angular provides two files in your environments folder:

  • environment.prod.ts
  • environment.ts

There’s not much to these files by default. For example, the environment.prod.ts file probably looks like the following:

export const environment = {
  production: true
};

These files are referenced when serving and building your application. For example, when you build your application for production, you’re probably used to running the following command:

ng build --prod

That’s actually shorthand for the following:

ng build --configuration=production

Your configurations are defined in your angular.json file. You’ll see the following in there:

"fileReplacements": [
  {
    "replace": "src/environments/environment.ts",
    "with": "src/environments/environment.prod.ts"
  }
]

When Angular builds your app, it swaps out the default environment file with the respective file that matches the configuration you specified. We can use that to our advantage and include other information we want to use within the application specific to the environment.

Within the environment.prod.ts file, let’s add a name property and give it a value of PROD.

export const environment = {
  name: 'PROD',
  production: true
};

Within the environment.ts file, let’s add a name property and give it a value of DEV.

export const environment = {
  name: 'DEV',
  production: false
};

Display Environment

Now we’re ready to display the environment name in our application. Open the component where you want to display the environment.

First, we need to import the environment.

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

Next, let’s create a variable called environmentName to hold our name value.

environmentName: string;

Within our ngOnInit event, we can assign the name value to the variable we just created.

ngOnInit(): void {
  this.environmentName = environment.name;
}

All that’s left to do is display it in the template!

{{ environmentName }}

If you wanted to use a different color depending on which environment you were in, you could always create a CSS class that styles the environment name. Use the ngClass directive to conditionally include the class based on the environment.

[ngClass]="{ 
  'env-dev': environmentName === 'DEV',
  'env-prod': environmentName === 'PROD' 
}"
Related Articles
About the Author

Front End Developer

https://nightwolf.dev