是否可以在Angular 2 html模板中直接访问全局变量? [英] Are global variables accessible in Angular 2 html template directly?

查看:158
本文介绍了是否可以在Angular 2 html模板中直接访问全局变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我把app.settings设置为

So I put in app.settings like

public static get DateFormat(): string { return 'MM/DD/YYYY';}

,然后在我的组件的html模板之一中,我想做这样的事情.

and then in one of my html template of a component I want to do something like this.

<input [(ngModel)]="Holiday" [date-format]="AppSettings.DateFormat"/>

在组件中,我有

import { AppSettings } from '../../../app.settings';

现在,无法在html模板中像这样访问.有什么办法吗?

Right now it's not accessible like this in html template. Is there any way?

推荐答案

否,模板中代码的作用域是组件实例.您需要将值分配给组件中的字段,或者添加转发到全局变量的getter或方法,以便能够从模板中使用它.

No, the scope for code in the template is the component instance. You need to assign the value to a field in the component, or add a getter or method that forwards to the global variable in order to be able to use it from the template.

import { AppSettings } from '../../../app.settings';

...
export class MyComponent {
  get dateFormat() {
    return AppSettings.DateFormat;
  }
}

然后您可以像使用它

<input [(ngModel)]="Holiday" [date-format]="dateFormat"/>

这篇关于是否可以在Angular 2 html模板中直接访问全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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