0
votes

I need to update from an Angular project a variable from external javascript file

First I import the variable in my Angular component, and then I try to update it but I don't know how to do it

Little example of my Angular component:

import { Component } from '@angular/core';
import { externalText } from './external.js';

...


export class AppComponent  {
  myText = externalText;

  changeText() {

    // This works, but I need to update the variable from external file directly
    this.myText = 'Text updated'

    // I need something like this 
    // externalText = 'Text updated'
  }
}

I create this Stackblitz with an example:

https://stackblitz.com/edit/angular-hczxhh

Expected: be able to update the information in the Javascript file from my Angular component

1
Please provide a minimal reproducible example as code in the question itself. This question becomes useless for future readers if/when the link dies. - AJT82
You can't save in a file using client-side script, you have to use some server-side scripting likePHP, NodeJS,.NET etc. to save something in a file. - jitender
I updated it with some code in the description - Jgascona
@Jgascona no you will need some server side code using ts or js only you can't do this - jitender
@Jgascona, I thinks you can't do this. If i were you, build a service to read the property from your external.js or from session cache. If you don't have any in cache them read from external.js. If you want update the value change the cache value. - Miguel Pinto

1 Answers

1
votes

Finally, I just created a function in my .js file that overwrites this variable with the content provided by angular. Then I exported this function in order to use it in the Angular component.

Javascript file:

export function updateText(myText) {
  externalText = myText
}

Angular component:

import { externalText, updateText } from './external.js';

export class AppComponent  {
  myText = externalText;

  changeText() {
    updateText('Problem solved')
  }
}

Thanks you all a lot for your answers.