Kabir Roy Kabir Roy - 1 year ago 145
TypeScript Question

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:


import { C0NST } from './constants';


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

However defining a member in the component class works:


private const constant = C0NST;


{{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.

Answer Source

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 thing 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download