Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

angular - Angular2 access global variables from HTML template

I have a global variable to store the list of countries like this:

export var COUNTRY_CODES = ["AD", "AE", "AF" /* and more */];

In one of my component, I'd imported the variable using normal import statement

import { COUNTRY_CODES } from "../constants";

I am able to access this global variable freely in my component code, but failed to achieve something like this on the HTML template:

<option *ngFor="let countryCode of COUNTRY_CODES" [value]="countryCode">{{countryCode | countryName}}</option>

I could just pass along the global variable to component by defining a local variable and assign the global variable to it during initialization.

ngOnInit() {
  this.countryCodes = COUNTRY_CODES;
}

And change the ngFor to loop on this local variable to make it works.

My question: Is this the right way to do? I'm not totally comfortable with defining bridging variables every time I want to use global variables in my template.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are creating a variable countryCodes in you component but the view is accessing COUNTRY_CODES instead*


Global identifiers like Array, window, document, class and enum names and global variables can't be accessed directly from within the template.

The scope of the template is the component class instance.

What you can do if you need access to any of these, is to create a getter in your component like

import { COUNTRY_CODES } from "../constants";

@Component(...)  
export class MyComponent {
  get countryCodes() { return COUNTRY_CODES; }
  // or countryCodes = COUNTRY_CODES;
}

then it can be used in the template like

<option *ngFor="let countryCode of countryCodes" [value]="countryCode">{{countryCode | countryName}}</option>

Using a shared service like suggested in the other answers works similar. What's the better approach depends on the concrete use case. Services are easy to mock for unit tests in contrary to global variables.

See also


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...