问题 Angular2中的ng-switch


我正在玩角度2(目前版本为alpha 26)。 ng-for 和 ng-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上的角度回购比较了 单元测试

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

  • 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>

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


7450
2018-06-09 06:24


起源



答案:


你需要导入 NgSwitchWhen 和 NgSwitchDefault,将这些添加到import语句中


11
2018-06-10 02:23



好的,就是这样。非常感谢,我从来没有发现过..但它是有道理的! - PzYon
在哪里进口那些? - Jimmy Kane


答案:


你需要导入 NgSwitchWhen 和 NgSwitchDefault,将这些添加到import语句中


11
2018-06-10 02:23



好的,就是这样。非常感谢,我从来没有发现过..但它是有道理的! - PzYon
在哪里进口那些? - Jimmy Kane