[Fixed] How to check feature is true on different environments in angular?

Issue

I am using different environments in angular, stored into the environments folder, like:

environment.ts
environment.dev.ts
environment.prod.ts

In the environment.ts file, I have:

export const environment = {
  production: false,
  environment: 'Development',
  advanced: {
    features: true
  }
};

I want to show a div element in page only if the environment has this advanced feature equal to true. I was thinking of doing :

import { environment } from './environments/environment';
export class AdvancedComponent implements OnInit {
  advancedFeatures:boolean;
  
  constructor() { }

  ngOnInit() {
    this.advancedFeatures= environment.advanced.features;

    if (this.advancedFeatures){
      console.log("true");
    }
    else {
      console.log('false');
    }
  }

}

Is this enough for hiding or showing a div element if the environment is dev or prod? Is this a good approach of the advanced feature from environment or should I somehow import all environments into this class?

Solution

Your environment.ts is the default config that’s used when you import the environment file.

And the reason Angular is able to pick the right environment file during build is by utilizing a fileReplacements section in its config settings (see ng docs). That way it ensures that you use the correct environment.advanced.features value in your code.

Similar to the prod version in fileReplacements, you could define any kind of setting (ie. dev or testing) and refer to the corresponding environment file.

As for the viability of your approach– personally I prefer using access roles to define which pages a user can see but I don’t see any particular disadvantages of your approach either.

Leave a Reply

(*) Required, Your email will not be published