Check out our Angular Book Series.

How to access a Constant in an Angular View Template?

Angular provides a mechanism for sharing instance variables inside a component with that template's view component, but how do you access a constant in a view template? Constants in TypeScript are not created as instance variables on a class, so they are not easily accessible inside the HTML template. This post will show you how.

The Setup

Create a new project with the Angular CLI. You can also get access to the full source code in my Blog Sample Github Repo.

Create the Constant File

Create a file in the root directory named constants.ts. Add in a single constant:


export const MY_TEST_CONSTANT = `Something`;

This is pretty simple.

Load the Constant in the Component

The trick to access the constant's value inside the view template is to copy the Constant value to an instance variable in the component. Open up the app.component.ts on your new project, and add a line like this:


myConstant = MY_TEST_CONSTANT;

You'll also need to import the constant:


import {MY_TEST_CONSTANT} from './Constants';

Update the View Template

Now the View Template can access the constants value. Open up the app.component.html file, ad add something like this:


<strong>Here is your Constant</strong>: {{myConstant}}

You're no longer referencing a global constant, but rather a component instance variable that has the same value as the global constant.

It works:

You can use the myConstant value as part of any Angular element in the HTML template including *ngIf, *ngFor, ngModel, or whatever you need.

Don't forget to check out the full code.

Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
All Content Copyright 2005, 2006, 2007, 2008, 2009 Jeffry Houser. May not be reused without permission
BlogCFC was created by Raymond Camden. This blog is running version 5.9.2.002.