ItSolutionStuff.com

How to Declare Global Variable in Angular 9/8?

By Hardik Savani • October 20, 2023
Angular

Today, i will show you how to create global variable in angular 9/8. we can define global variable in angular 9/8 application. i will give you simple example of global variables in angular 9/8.

We always need to declare global variable file for our angular 8 application because we can set some global variable there like site title, api url etc so you can easily access any where in our application easily.

So, in this example, we will create GlobalConstants file for adding global variables in our application. in that file i added two variables as apiURL and siteTitle. I will access those variable value in my AppComponent file. you can also access all the component as you want.

Now, bellow we will create GlobalConstants as like created bellow and We will use that variables as like used in AppComponent file.

src/app/common/global-constants.ts

export class GlobalConstants {

public static apiURL: string = "https://itsolutionstuff.com/";

public static siteTitle: string = "This is example of ItSolutionStuff.com";

}

src/app/app.component.ts

import { Component, OnInit } from '@angular/core';

import{ GlobalConstants } from './common/global-constants';

@Component({

selector: 'app-root',

templateUrl: './app.component.html',

styleUrls: ['./app.component.css']

})

export class AppComponent implements OnInit{

title = GlobalConstants.siteTitle;

constructor() {

console.log(GlobalConstants.apiURL);

}

ngOnInit() {

console.log(this.title);

}

}

Now you can check this project and run it.

It will display as like bellow:

Output:

https://itsolutionstuff.com/

This is example of ItSolutionStuff.com

Angular is running in the development mode. Call enableProdMode() to enable the production mode.

Object

Live Reloading enabled.

I hope it can help you...

Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube

We Are Recommending You

Angular 9/8 Highcharts Example Tutorial

Read Now →

Angular 8 Image Upload with Preview

Read Now →

How to use Datepicker in Angular 9/8?

Read Now →

How to Create Reusable Components in Angular 10/9/8?

Read Now →

Angular Font Awesome - How to install font awesome in Angular 9/8?

Read Now →

How to Create Custom Validators in Angular 9/8?

Read Now →

How to Create New Component in Angular 8?

Read Now →

Angular NgClass - How to Add Dynamic Class in Angular 10/9/8?

Read Now →

How to Create Custom Pipe in Angular 9/8?

Read Now →