从模板访问常量

时间:2016-11-22 18:26:57

标签: angular typescript

我有一个简单的组件player-card.component.ts

export const CONTENT_CARD_META = {
    "rank": "Rank",
    "age": "Age",
    "gender": "Gender",
    "race": "Race"
};

export const CONTENT_CARD_META_KEYS = [ "rank", "age", "gender", "race" ];

@Component({
    moduleId: module.id,
    selector: 'player-card',
    templateUrl: 'player-card.component.html'
})
export class PlayerCardComponent {
    player: Player = {
        id: '1',
        rank: 'C',
        age: 10,
        gender: 'male',
        race: 'human'
    };
}

它的模板

<ul class="nav nav-tabs" role="tablist">
    <li class="nav-item">
        <a class="nav-link active" id="playerCard-tab"
           data-toggle="tab" href="#playerCard" role="tab" aria-expanded="true" aria-controls="playerCard">Guild card</a>
    </li>
    <li class="nav-item">
        <a class="nav-link" id="magicCard-tab" data-toggle="tab" href="#">Magic card</a>
    </li>
</ul>
<div class="tab-content">
    <div class="tab-pane fade in active" id="playerCard" role="tabpanel" aria-labelledby="playerCard-tab">
        <div class="card">
            <div class="card-block">
                <h4 class="card-title text-muted">{{player.name}}</h4>
                <h6 class="card-subtitle text-muted">
                    Adventurer card
                </h6>
            </div>
            <img data-src="holder.js/200px200/?text=Image">
            <div class="card-block">
                <div class="form-group row" *ngFor="let key of CONTENT_CARD_META_KEYS">
                    <player-record [label]="CONTENT_CARD_META[key]" [value]="player[key]"></player-record>
                </div>
            </div>
        </div>
    </div>
</div>

当我喜欢这个时

<div class="form-group row" *ngFor="let key of CONTENT_CARD_META_KEYS">
    <player-record [label]="CONTENT_CARD_META[key]" [value]="player[key]"></player-record>
</div>

它不起作用。但是当我在PlayerCardComponent

中创建字段时
export class PlayerCardComponent {
    cartContent = CONTENT_CARD_META;
    keyCartContent = CONTENT_CARD_META_KEYS;

并且喜欢这样

<div class="form-group row" *ngFor="let key of keyCartContent">
    <player-record [label]="cartContent[key]" [value]="player[key]"></player-record>
</div>

工作正常。 如何在组件模板中使用const变量?

1 个答案:

答案 0 :(得分:5)

在模板中仅可用当前组件类实例提供的内容。

如果要访问组件实例之外的任何内容,则需要在组件实例内部进行一些允许伸出的引用。

无处可去。