How to define global constants(variables) in angular

In this article, I’ll show you how to define global constants(variable) in angular. This is often a requirement in most of the application.

Global constants is useful when you are creating an angular application and you want to initialize some common variables that can be used in multiple components.

Think of an application where we’re showing lots data tables over an application and consistency is a good practice while building any application. so we want datatable to be consistence all over the application.

For example, we want to show the same number of items per page and page size option(dropdown to select items per page) and allow filtering and etc. Anything you can think that can be reused across all the components.

Now I’ll show you how to define global variables in angular.

You can create a class and then you can define static variable in it as following:
src/app/global/datatable-constants.ts


export class DataTableConstants {
    public static ItemPerPage: number = 50;
    public static PageSize: number[] = [10, 50, 100, 200, 500];
    public static AllowFiltering: boolean = true;
}

You define global variables as above and you can use in component as follows:
src/app/app-example.component.ts


import { Component, OnInit } from '@angular/core';
import { DataTableConstants } from './globals/datatable-constants';
   
@Component({
  selector: 'app-example',
  templateUrl: './app.example.html',
  styleUrls: ['./app.example.css']
})
export class AppExampleComponent implements OnInit{
    itemPerPage = DataTableConstants.ItemPerPage;
    pageSize = DataTableConstants.PageSize;
    allowFiltering = DataTableConstants.AllowFiltering;
  
    ngOnInit() { 
        console.log(this.itemPerPage);
        console.log(this.pageSize);
        console.log(this.allowFiltering);
    }
}

and that’s it, you can use that variable as above and it’ll output the following values in console.

How to define global constants(variables) in angular
Output of angular global constants variable.

I hope you’ll like this article.

Also Read: