Creating a worldwide variable in Angular 6 using Typescript

Two files exist, one named 'Drawer.ts' and the other is the

'sidenav-open-close.component.ts'
component.

A variable needs to be shared between these two files. It should have the flexibility to be updated in 'Drawer.ts', with the

'sidenav-open-close.component.ts'
responding accordingly.

An attempted method was using the following link - What is the best way to declare a global variable in Angular 2 / Typescript and creating a file called globals.ts with this content:

'use strict';
export var diffMode : boolean = false;

This file was then imported into both files using

import * as myGlobals from './src/globals.ts';

The variable diffMode could be read successfully, but encountering an error when attempting to update it through 'Drawer.ts':

ERROR TypeError: Cannot set property diffMode of [object Object] which has 
only a getter

Your assistance would be greatly appreciated. Thank you.

Answer №1

Utilizing JavaScript modules (known as "ESM" for ECMAScript Module), which TypeScript currently incorporates, allows imports to serve as a read-only perspective of the export. This is the reason why altering diffMode from an external module where it was originally defined is not possible.

In the event that there is a necessity to modify its value from another module, a function can be exposed for this purpose:


export var diffMode : boolean = false;
export function setDiffMode(flag: boolean) {
    diffMode = flag;
}

By invoking this function from the external module rather than directly editing it, changes to diffMode can be successfully implemented.

Interactive Example (JavaScript-based proof of concept) hosted on plunker (Please note that Stack Snippets do not support modules).

main.js:

const handle = setInterval(() => {
    const p = document.createElement("p");
    p.appendChild(
        document.createTextNode(`diffMode = ${diffMode}`)
    );
    document.body.appendChild(p);
}, 250);
setTimeout(() => {
    clearInterval(handle);
}, 1000);

export var diffMode = false;
export function setDiffMode(flag) {
    diffMode = flag;
}

othermod.js:

import {diffMode, setDiffMode} from "./main.js";

setTimeout(() => {
    setDiffMode(true);
}, 500);

The execution of the mentioned code illustrates the capacity of othermod.js to effectively modify diffMode, with these alterations being duly recognized by the functionality within main.js.


A side observation to make: Modules automatically operate in strict mode, rendering the inclusion of 'use strict'; at the beginning unnecessary.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Refine JSON arrays by applying combined nested array filters

Currently, I am in the process of developing a JavaScript code that aims to filter JSON data based on a specific condition. Yesterday, I had posted a question seeking guidance on this matter How to filter data from a json response. However, since I had not ...

Steps for changing an array of objects from a string into a regular array of objects

I am facing an issue where I have an array of objects in string format that I need to convert into a normal array of objects. I tried using the JSON.parse() method for conversion, but when attempting to access values like: this.contact_data[0].data.value, ...

Is there a way for me to display both the right and wrong answers in real-time as users make their selections on my multiple-choice question website? Additionally, can I track the number

I've just implemented the code for my multiple-choice question (MCQ) website. One of the key features I want to include is immediate feedback when a user selects an answer - indicating whether it is correct or incorrect along with showcasing the corre ...

Revisiting Async Await: A guide to implementing callbacks

I have the following code snippet: const myImage = document.querySelector('img'); const myRequest = new Request('flowers.jpg'); fetch(myRequest).then((response) => { console.log(response.type); // returns basic by default respo ...

The AngularJS ngModelController is a powerful tool for managing

How can I accurately check ngModelController validity? Within my directive, I have a controller object. When I console.log the object from inside the directive, it displays: console.log(ctrl) $dirty: false $invalid: true $modelValue: "" $name: undefined ...

The uncomplicated node.js function is providing an unexpected result of undefined rather than an

Currently, I am delving into nodejs and encountering some issues with a basic function. The purpose of this function is to create an array; however, the problem arises when attempting to assign the result to another variable. Strangely, the variable always ...

Extract the array of numbers from the JSON file

My task is to extract an array of numbers from JSON files. I need to handle files that contain only arrays of numbers or one level deeper (referred to as direct arrays). These files may also include other data types such as strings or booleans. The challe ...

Tips on implementing pdf-lib in Angular?

I came across the pdf-lib library and am interested in incorporating it into my Angular project. However, I couldn't find any documentation on how to import it specifically for Angular. Can anyone assist me with the process of importing this library ( ...

Update a single javascript variable on every rotation of the Bootstrap carousel

Within my website, I have implemented a popin/modal feature using Hubspot Messenger which includes a Bootstrap 3 carousel. Each slide of the carousel displays a different "social embed" such as Facebook or Twitter, and I am looking to adjust the width of t ...

Something seems to be missing in Vue.js as it cannot compute the property 'length' of null

When I attempt the following: <div class="panel panel-default" v-if="socialiteLogins !== null"> The panel remains visible. Checking socialiteLogins === null or with == both indicate that the object is not null, even though it actually is. When dump ...

Transferring data in PDF format through email with the help of PHPMailer and html2pdf

Having trouble sending PDF or PNG files over email despite multiple attempts. Despite reading countless articles on the topic, nothing seems to be working as suggested. Can anyone provide assistance? I am using PHPMailer along with html2pdf and html2canva ...

404 error occurs when trying to access the email address parameter in Angular 2

I have a group of URLs that are linked by a common theme: http://localhost:3000/account/changeforgottenpassword (200OK, PASS) http://localhost:3000/account/changeforgottenpassword/testexample/75c09b18-6090-44df-a18d-d1fe06ab1cde (200OK, PASS) http://loca ...

After I click on an operator button, the display on my HTML calculator does not reset

function aClick(){ if(a === undefined){ numberButtons.forEach(button => { button.addEventListener("click", addNumber) }); operatorButtons.forEach(button => { button.addEventListener(' ...

Encountering problems with concatenating strings due to encoding difficulties

When working with two HTML datalists, I extract their input values to query a JSON file. Initially, I search for the keys in my JSON file, which represent college majors, with their corresponding values being the courses. By matching the object key with th ...

Customized Bootstrap Dropdown with the ability to add text dynamically

I am working on a Bootstrap dropdown menu that allows users to generate expressions by clicking on the menu items. For example, when the "Action" item is clicked, it should insert {{Action}} into the textbox. The user can then type something like "Hello" a ...

Having trouble loading background color or image in three.js

I've been struggling to load a background image or color on my webpage. Despite trying various methods, including commenting out javascript files and checking the stylesheet link, nothing seems to work. Even when I load the three.js scene with javascr ...

Is it appropriate to include JavaScript and CSS in views?

In my ASP.NET MVC project, I have set up a _Layout, a controller, and several views. Certain pieces of code are clearly global in nature, such as the CSS included in the _Layout file and other styles that are consistent throughout the site. However, when ...

What possible reason is causing ag grid to overlook the defaultExcelExportParams option that was provided?

Here is my React ag grid code snippet. I'm trying to implement the processCellCallback function, but unfortunately, I am not seeing the console.log output in the browser console when exporting excel. Any suggestions on what might be causing this issue ...

Having trouble with the Bootstrap 4 toggle functionality while converting a Bootstrap theme to an Angular 9 project?

I am currently in the process of converting a Bootstrap theme to an Angular 9 project. I have successfully configured all the necessary JS and CSS files in the angular.json file, but unfortunately, the toggle function is not working. Please take a look at ...

Find what you're looking for by exploring the search results inside the text box marked

update1: Appreciate your response! However, I am facing an issue where typing 'h' displays a set of values. When selecting a value, it should appear in the text box with a cross symbol, similar to how tags are edited on StackOverflow. I am work ...