Angular2中的ng-switch

PzY*_*Yon 11 typescript ng-switch 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;
}
Run Code Online (Sandbox Code Playgroud)

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

我不知道,为什么它不起作用.从我的理解,一切都应该是正确的.我与github上的角度回购,单元测试等进行了比较.

这些是我检查的东西,我相信是可以的:

  • 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>
Run Code Online (Sandbox Code Playgroud)

这也不起作用,所以它必须是一些非常基本的东西,我做错了.我恐怕在互联网上找不到任何例子或代码片段.任何帮助将不胜感激,提前谢谢.

uno*_*obf 11

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