How to Define Global Variable in Angular 16?
Hey Folks,
Here, I will show you how to work angular 16 global variable for all components. I explained simply about global variable in angular 16. This article will give you a simple example of dynamic global variable in angular 16. It's a simple example of angular 16 access global variable.
We always need to declare a global variable file for our angular 16 application because we can set some global variables there like site title, API URL, etc so you can easily access anywhere in our application easily.
So, in this example, we will create a GlobalConstants file for adding global variables in our application. in that file I added two variables appURL and appTitle. I will access those variable values in my AppComponent file. you can also access all the components as you want.
Now, bellow we will create GlobalConstants as created bellow and We will use that variable as like used in the AppComponent file.
src/app/common/global-constants.ts
export class GlobalConstants {
public static appURL: string = "https://itsolutionstuff.com/";
public static appTitle: string = "This is example of ItSolutionStuff.com";
public static appLogo: string = "assets/images/logo.png";
public static appEmail: string = "example@gmail.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.appTitle;
url = GlobalConstants.appURL;
email = GlobalConstants.appEmail;
constructor() {}
ngOnInit() {}
}
Now you can check this project and run it.
It will display as like below:
Output:
This is example of ItSolutionStuff.com
https://itsolutionstuff.com/
example@gmail.com
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
- Angular 16 CRUD Application Tutorial Example
- Angular 16 Integrate Google Maps Example
- Angular 16 Stripe Payment Integration Example
- Angular 16 Google Social Login Example Tutorial
- Angular 16 HttpClient & Http Services Tutorial
- Angular 16 Pagination with NGX Pagination Example
- Angular 16 RxJS Observable with Httpclient Example
- Angular 16 Routing and Navigation Example Tutorial
- Angular 16 Service Tutorial with Example
- Angular 16 Template Driven Form Validation Example
- Angular 16 Multiple File Upload Example Tutorial
- Angular 16 Multiple Image Upload with Preview Example
- Angular 16 Material Datepicker Example Tutorial
- Angular 16 Install Moment JS Example
- Angular 16 File Upload Tutorial Example