2016-12-06 69 views
2

是否可以在不在this上下文中的Angular 2模板中使用變量?Angular2模板 - 不使用變量

例如:

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

fooBar需要在此組件使用的類中定義的地方,例如:

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

但是,如果你只是想用一個值,這不是什麼班上?比如,也許你要導入的字符串常量的列表,並在模板中選擇顯示它們:

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

只是分配一個列表到類變量? – Dimanoid

回答

2

我看到兩種方法來實現它:

1)組件定義變量名稱相同爲您不斷

export class MyComponent { 
    StringConstants = StringConstants; 
    ... 

2)使用ES6串插

template:` 
    <div *ngIf="isPrimary">${StringConstants.PRIMARY}</div> 
    <div *ngIf="isSecondary">${StringConstants.SECONDARY}</div> 
` 
export class MyComponent { 
+0

要清楚:看起來像選項2只有在模板被內聯而不是外部時纔有效。 –