Angular2从HTML模板访问全局变量 [英] Angular2 access global variables from HTML template

查看:282
本文介绍了Angular2从HTML模板访问全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个全局变量来存储这样的国家/地区列表:

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

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

在我的组件之一中,我使用普通的import语句导入了变量

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

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

我能够在自己的组件代码中自由访问此全局变量,但是无法在HTML模板上实现类似的功能:

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;
}

并更改ngFor以在此局部变量上循环以使其起作用.

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.

推荐答案

您正在组件中创建变量countryCodes,但是视图正在访问COUNTRY_CODES *

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

不能直接从模板内部访问全局标识符,例如Arraywindowdocument,类和枚举名称以及全局变量.

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;
}

然后可以在模板中使用

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

另请参见

  • Select based on enum in Angular2
  • How to bind a list in Angular2?

这篇关于Angular2从HTML模板访问全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆