11

我正在玩 angular 2(目前使用 alpha 26 版本)。例如工作正常ng-forng-if但是,我确实有问题ng-switch。我只是无法让它工作,即没有打印任何内容。似乎整个模板都被忽略了。

这是我的组件中的代码,也可以在github上找到:

import {Item} from "js/types/item";
import {Component, View, NgFor, NgIf, NgSwitch} from "angular2/angular2";

@Component({
    selector: "item-details",
    properties: [
        "item"
    ]
})
@View({
    template: `<span>You selected {{item.name}},</span>
               <span [ng-switch]="item.name">
                 <template [ng-switch-when]="'Bill'">
                   <span> who is often called Billy.</span>
                 </template>
                 <template [ng-switch-when]="'Bob'">
                   <span> who is often called Bobby.</span>
                 </template>
                 <template [ng-switch-default]">
                   <span>who has no nickname.</span>
                 </template>
               </span>
               <div *ng-if="item.subItems">
                 <h2>Sub items:</h2>
                 <ul>
                   <li *ng-for="#subItem of item.subItems">{{subItem.name}}</li>
                 </ul>
               </div>`,
    directives: [NgFor, NgIf, NgSwitch]
})
export class ItemDetailsComponent {
    item:Item;
}

name基本上它是一个简单的组件,我将一个具有属性的项目注入其中。该name属性确实有一个值,我可以看到该行<span>You selected {{item.name}},</span>工作正常。

我不知道,为什么它不起作用。根据我的理解,一切都应该是正确的。我与 github 上的 angular repo、单元测试等进行了比较。

这些是我检查过的,我相信没问题:

  • NgSwitch通过导入和注入directives
  • 语法正确
  • item确实可用(但可能不在上下文中NgSwitch?)

为了确定这一点,我还尝试了一些简单的方法,例如以下模板(切换硬编码的字符串或数字):

<span [ng-switch]="'foo'">
 <template [ng-switch-when]="'foo'">
   <span> who is often called foo.</span>
 </template>
 <template [ng-switch-when]="'bar'">
   <span> who is often called bar.</span>
 </template>
</span>

这也不起作用,所以它一定是我做错了的一些非常基本的事情。恐怕我在互联网上找不到任何示例或代码片段。任何帮助将不胜感激,在此先感谢。

4

1 回答 1

12

您需要导入NgSwitchWhenNgSwitchDefault,将这些添加到导入语句

于 2015-06-10T02:23:55.717 回答