Angular CLI Passing Environment Variable in command

Viewed 1568

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.

1 Answers

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.

Related