How to use environment variable in index.html for Angular 6

Viewed 59473

I am using angular6, in my project I am using Facebook Account Toolkit for mobile verification purpose.

I need to initialise Account toolkit in index.html file using following code.

  AccountKit.init({
   appId:"XX",
   state:"xx",
   version:"v1.2",
   fbAppEventsEnabled:true,
   debug:true
 });

The problem is, values for appId and state change depending on environment (development/test/production).

How can I use environment variables in index.html file.

Please let me know if anyone has a solution for angular 6.

Thanks in advance.

9 Answers

You should create copy of index.html and name it index.someenv.html. Then in your angular.json in environment configuration setup file replacement:

"fileReplacements": [
    {
        "replace": "src/index.html",
        "with": "src/index.someenv.html"
    }
]

The angular cli will replace these files when you run your build

This answer supersedes Artyom's answer for Angular 8 and above. Add the following to your angular.json:

"production": {
  "index": {
    "input": "src/index.someenv.html",
    "output": "index.html"
  },
},

An example here for document.write(environment.variable) : https://github.com/angular/angular-cli/issues/4451#issuecomment-285026543

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

if (environment.production) {
  document.write('<script type="text/javascript">// ProductionAnalyticsCodeHere</script>');
} else if (environment.staging) {
  document.write('<script type="text/javascript">// StagingAnalyticsCodeHere</script>');
}

In main.ts file you can use document.write(environment.variable) and it will write what you want in index.html

(I use it to make the Google Analytics script take a dynamic Tracking ID wether it's in development or production mode, and it works well in Angular6)

for me above answers did not work on Angular 10, so I created different folder for staging, production etc and placed the index.html which was used by CLI as per the build environment

{
  "projects": {
    "yourApp": {
      "projectType": "application",
      "root": "",
      "sourceRoot": "src",
      "prefix": "app",
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "index": "src/index.html",
          },
          "configurations": {
            "production": {
              "index": "src/production/index.html",
            }
          }
        }
      }
    }
  }
}     

I think you can do it all in main.ts

const env = environment;

 AccountKit.init({
   appId:env.appId,  // this lane
   state:env.state,  // this lane
   version:"v1.2",
   fbAppEventsEnabled:true,
   debug:true
});

Thanks.

I added this in main.ts:

var html = document.documentElement.innerHTML
document.documentElement.innerHTML = html.replace("Replace me!", environment.variable)

Note that the old value will still exist in index.html for some time while the page is initially loading. (For example, use this to replace the page title and you'll see the old value displayed before the replace happens.)

Avoid direct access to the document object by injecting DOCUMENT to your AppComponent.

import { DOCUMENT } from '@angular/common';
...
  public constructor(
    @Inject(DOCUMENT) private doc: any
  ) {

Add the tag in ngOnInit()

ngOnInit() {
    this.setYourScriptTag();
}

private function to set it

  private setYourScriptTag() {
    const s = this.doc.createElement('script');
    s.type = 'text/javascript';
    s.innerHTML = `AccountKit.init({
   appId: "${environment.appId}",
   state: "${environment.state}",
   version:"v1.2",
   fbAppEventsEnabled:true,
   debug:true
 });`;
    const head = this.doc.getElementsByTagName('head')[0];
    head.appendChild(s);
  }

This answer is from edodusi

https://github.com/angular/angular-cli/issues/4451#issuecomment-384992203

import your environment file into .ts file.

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

Create required fields in your class, assign values from environment to these variables in the constructor, use usual binding in the .html file.

.ts

import { Component } from '@angular/core';
import { environment } from '../environments/environment';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  public production = true;
  constructor() {
    this.production = environment.production;
  }
}

.html

<span>{{production}}</span>
Related