2016-12-06 4 views
2

thisコンテキストにないAngular 2テンプレートの変数を使用できますか?例えばAngular2テンプレート - これには変数を使用しない

:あなただけではありません値を使用したい場合は

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

しかし、どのような:

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

fooBarは次のように、どこかにこのコンポーネントで使用するクラスで定義する必要がありますクラス?

1)コンポーネントで変数を定義し、同じ名前を持つ:

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

が、私はそれを達成する2つの方法を参照してください。たとえば、多分あなたは、文字列定数のリストをインポートし、テンプレートで選択的にそれらを表示したいですあなたの定数

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は、テンプレートが外部ではなくインライン化されている場合にのみ機能するように見えます。 –

関連する問題