2017-01-03 51 views
1

所以我把在app.settings像是直接在Angular 2 html模板中訪問的全局變量嗎?

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

,然後在我想要做的是這樣的一個組成部分的我的HTML模板之一。

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

在組件我有

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

現在它不是在HTML模板這樣的訪問。有什麼辦法嗎?

回答

2

不,模板中的代碼範圍是組件實例。您需要將值分配給組件中的某個字段,或者添加一個轉發到全局變量的getter或方法,以便能夠從模板中使用它。

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

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

那麼你可以使用它像

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

據我所知,沒有的,這是由設計。模板與組件結合在一起,這就是它們如何派生它們的範圍並從而訪問可綁定數據的方式。它有可能被黑客攻破,但即使你弄明白了,這也是一條你不應該遵循的道路。

我做這樣的事情一類:

class AppConfig {} 

AppConfig.Globals = { 
    TEST_VAL: 'hey now here is the value' 
}; 
export { AppConfig } 

,然後用它像這樣:

import { Component } from '@angular/core'; 
import { AppConfig } from '../../app/app.config'; 

class HomeComponent { 
    constructor() { 
     this.test_val = AppConfig.Globals.TEST_VAL; 
    } 
} 

HomeComponent.annotations = [ 
    new Component ({ 
     templateUrl: './views/home/home.component.html' 
    }) 
]; 

export { HomeComponent } 

在模板:

{{test_val}} 

很適合我。

+0

請注意,如果您對此更熟悉,則可以在該AppConfig文件中使用導出的常量。 –