Angular

How to Declare Global Variable in Angular 15?

Pinterest LinkedIn Tumblr

In Angular 15, you can declare a global variable by creating a new file in the root of your project and exporting a variable or an object from that file.

Here’s an example of how you can create a global variable in Angular 15:

  1. Create a new file in the root of your project, for example global.ts
  2. In this file, declare a variable or an object you want to use as a global variable:
Copy codeexport const globalVariable = {
    url: 'https://example.com'
};
  1. In any component or service that you want to use this global variable, import it:
Copy codeimport { globalVariable } from './global';
  1. Now you can use the global variable in your component or service.
Copy codeconsole.log(globalVariable.url);

Note that this approach will make the variable available throughout the entire application and can be accessed from any component or service. Also, it should be used with caution since it can make your codebase harder to understand and maintain.

Another approach is to use a shared service. Services are singleton, so you can create a service that contains the variables and inject it in the components or services where you need the global variables.

Write A Comment