Angular Define Global Variables Tutorial
In this tutorial, we will learn how declare global variable in angular app. we will simple create global variables file in angular. we can create global variable for all components in angular application.
we can easily define global variable file in angular 6, angular 7, angular 8, angular 9, angular 10, angular 11, angular 12, angular 13, angular 14, angular 15, angular 16 and angular 17 application.
We always need to declare global variable file for our angular 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
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- How to use Highcharts in Angular?
- Angular Image Upload Example Tutorial
- Angular Material Datepicker Example
- How to Install And Use JQuery in Angular?
- Angular FormGroup Example Tutorial
- Angular Ng-Content Example Tutorial
- Angular Service with Httpclient Example
- How to Get Query String from URL in Angular?
- Angular Http Post Request Example
- Angular Change Date Format in Component Example