Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are global variables accessible in Angular 2 html template directly?

So I put in app.settings like

public static get DateFormat(): string { return 'MM/DD/YYYY';}

and then in one of my html template of a component I want to do something like this.

<input [(ngModel)]="Holiday" [date-format]="AppSettings.DateFormat"/>

In component I have

import { AppSettings } from '../../../app.settings';

Right now it's not accessible like this in html template. Is there any way?

like image 778
NoStressDeveloper Avatar asked Jan 03 '17 19:01

NoStressDeveloper


People also ask

Can global variables be accessed anywhere?

Variables that are created outside of a function are known as Global Variables . A global variable is one that can be accessed anywhere . This means, global variable can be accessed inside or outside of the function.

Are global constants accessible from anywhere in a program?

You can access the global variables from anywhere in the program. However, you can only access the local variables from the function. Additionally, if you need to change a global variable from a function, you need to declare that the variable is global. You can do this using the "global" keyword.

Is there any global variable in Angular?

We always need to declare global variable file for our angular 10 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.


1 Answers

No, the scope for code in the template is the component instance. You need to assign the value to a field in the component, or add a getter or method that forwards to the global variable in order to be able to use it from the template.

import { AppSettings } from '../../../app.settings';

...
export class MyComponent {
  get dateFormat() {
    return AppSettings.DateFormat;
  }
}

then you can use it like

<input [(ngModel)]="Holiday" [date-format]="dateFormat"/>
like image 189
Günter Zöchbauer Avatar answered Sep 24 '22 07:09

Günter Zöchbauer