2

Is it possible to use a variable in an Angular 2 template that is not on the this context?

For example:

<div>{{ fooBar }}</div>

fooBar needs to be defined in the class used by this component somewhere, like:

export class MyComponent {
  public fooBar: boolean = true;
}

But what if you just want to use a value that's not on the class? For example, maybe you want to import a list of string constants and display them selectively in the template:

import { MyService } from './my.service'; 
import { StringConstants } from '../string.constants';

@Component({
  selector: 'my-component',
  template: `
    <div *ngIf="isPrimary">{{ StringConstants.PRIMARY }}</div>
    <div *ngIf="isSecondary">{{ StringConstants.SECONDARY }}</div>
  `
})

export class MyComponent {
  public isPrimary: boolean;
  public isSecondary: boolean;

  constructor (private myService: MyService) {
    this.isPrimary = myService.getPrimaryContext();
    this.isSecondary = myService.getSecondaryContext();
  }
};
1
  • 1
    Just assign that list to a class variable? Commented Dec 6, 2016 at 21:02

1 Answer 1

2

I see two ways to achieve it:

1) Define variable in component with the same name as your constant

export class MyComponent {
  StringConstants = StringConstants;
  ...

2) Use es6 string interpolation

template:`
  <div *ngIf="isPrimary">${StringConstants.PRIMARY}</div>
  <div *ngIf="isSecondary">${StringConstants.SECONDARY}</div>
`
export class MyComponent {
Sign up to request clarification or add additional context in comments.

1 Comment

To be clear: looks like option 2 will only work if the template is inlined, not external.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.