HDTuto.com

Angular 8 Define Global Variable Example



This tutorial is focused on declare global variable in angular 8. Here you will learn global variables in angular 8. if you have question about how to create global variable in angular 8 then i will give simple example with solution This article will give you simple example of angular 8 define global variable. So, let's follow few step to create example of angular 8 set global variable.

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://hdtuto.com/";

public static siteTitle: string = "This is example of hdtuto.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://hdtuto.com/

This is example of hdtuto.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...




February 13, 2020 | Category : AngularAngular 8
Related Posts



Blog Search


Copyright © 2020 HDTuto.com. All rights reserved.