Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access a constant in an Angular 2 component and service?

I have a constants file constants.ts:

export const C0NST = "constant"; 

I access it in a service some.service.ts like so:

import { C0NST } from './constants';  console.log(C0NST); // "constant" 

However, when I access it in a component template:

some.component.ts:

import { C0NST } from './constants'; 

some.component.html:

{{ C0NST }} <!-- Outputs nothing --> 

However defining a member in the component class works:

some.component.ts

public const constant = C0NST; 

some.component.html

{{ constant }} <!-- constant --> 

I don't understand why I was able to access the imported constant directly in the service class but not in the component template even though I imported it in the component class.

like image 737
Karma Avatar asked Oct 25 '16 10:10

Karma


People also ask

What is constant in angular?

Constant are like services in AngularJS in which we can define our globally data. It is declare using "constant" keyword. As we define our app-keys in Web.

What is the use of const in angular?

const lets us declare variables which don't change over time, which are immutable. The important gotcha with const is that the variable is immutable, but not the value, the thing the variable points to. This means that if we declare an object as const , confusingly we can still change properties of the object later on.

What is an angular 2 component?

Components are a logical piece of code for Angular JS application. A Component consists of the following − Template − This is used to render the view for the application. This contains the HTML that needs to be rendered in the application. This part also includes the binding and directives.


1 Answers

In Angular2, the template can only access fields and methods of the component class. Everything else is off-limits. This includes things which are visible to the component class.

The way to go around this is to have a field inside the component, which just references the constant, and use that instead.


It's one limitation of the design, but perhaps you should think a bit more about why you need a constant in the template in the first place. Usually these things are used by components themselves, or services, but not the template.

like image 132
Horia Coman Avatar answered Sep 29 '22 14:09

Horia Coman