Access javascript variable in component in Angular 5

Issue

I have a js file in my Angular application, data.js . This js file has some variables declared in it, something like below.

 var data = 'test'

Now I have to access these variables and their values in my component (app.component.ts).

I read some where that declaring them as exports make them into modules and those can be accessed anywhere, But I’m not sure how this can be done.

This is the structure of my application. I have data.js in assets->js folder.I need to modify the variable value in app.component.ts.

enter image description here

I’m very new to Angular. Is this even possible?

Solution

With the file in your assets, I am guessing you are declaring it on the window. You will need the include the script in your index.html, and then access it on the window within your component via window.data. This is not really the recommended way of doing this unless your use case dictates it. The module approach you mentioned is preferred.

Next to your app.component.ts, create a file called data.ts, with:

export let data: string = 'data';

In your app.component.ts, import it using:

import { data } from './data.ts';

If you plan to not mutate that data, consider using the const keyword instead (in data.ts).

Directory structure

/app.component.ts
/data.ts
/...

Edit: Show Global Approach

You will need to include your script outside of the context of the Angular application. If you bootstrapped your application using the Angular CLI, you can add a reference to it in the cli configuration file. See this documentation on the topic.

That file will be included and will be available for access within your component on the window. The tricky part comes with typing and the Window. And example may look like this.

class AppComponent extends Component {

     private data: string;
     constructor() {
       // Explicitly cast window as an any type.  Would be better to type this, but this should work for you.
       this.data = (<any>window).data;
     }       

}

Answered By – William Fleming

Answer Checked By – Candace Johnson (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.