4

Is there any way to pass some parameters when using angular cli command like ng build or especially in my case ng serve to change or set variables in environment without changing environment file or define new environment each time?

For example I have this environment.ts file

    export const environment = {
     apiData: true,
     authentication: true,
     checkValidation: true,
     signData: false,
     mockFileDirectoryUrl: '/assets/',
     saveUrl: 'http://localhost:5000/'
     getUrl: 'http://localhost:5005/'
    };

And I want to run my app in local for test with signData=true flag and different SaveUrl with a command like:ng serve signData true saveUrl "https:/localhost:5050"

I have found this approach How to pass environment variables at building time in an Angular application using .env files but the problem is with this solution each time the environment file is completely rewrote but I want pass these variables just in runtime.

6
  • You can create separate environment files for normal serve and for prod mode environment.ts and environment.prod.ts respectively, this will be an easier method if you have many variables to pass. Commented Jul 22, 2020 at 8:23
  • @BINFASK I have separate environment for production but on local I have many flags on my environment which I want to change some of them under some circumstances otherwise I should change the environment each time. Commented Jul 22, 2020 at 8:26
  • Does this medium.com/@ferie/… help? Commented Jul 22, 2020 at 8:36
  • @huanfeng Thank you but I have linked to this approach in my question and I have explain why this can't help me Commented Jul 22, 2020 at 8:38
  • This could help you medium.com/@balramchavan/… Commented Jul 22, 2020 at 8:38

1 Answer 1

5

Check out @ngx-env/builder, it exposes environment variables like these:

NG_APP_ENABLE_ANALYTICS=false
NG_APP_VERSION=$npm_package_version
NG_APP_COMMIT=$GITHUB_SHA

as global variables:

@Component({
  selector: "app-footer",
})
export class FooterComponent {
  version = process.env.NG_APP_VERSION;
  branch = process.env.NG_APP_BRANCH_NAME;
  commit = process.env.NG_APP_COMMIT;
  analyticsFlag = process.env.NG_APP_ENABLE_ANALYTICS;
}

and via a pipe:

<!-- Same output in the spans -->
<span> {{ 'process.env.NG_APP_BRANCH_NAME' | env }} </span>
<span> {{ 'NG_APP_BRANCH_NAME' | env }} </span>
<span> {{ branch }} </span>

Examples courtesy of the project readme.

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

Comments

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.