ng-switch in Angular2

一笑奈何 提交于 2019-12-08 15:27:06

问题


I am playing around with angular 2 (currently with version alpha 26). ng-for and ng-if for example are working fine. I do however have problems with ng-switch. I just can't get it to work, i.e. nothing is printed. It seems as if the whole template is ignored.

This is the code from my component, which can also be found on 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;
}

Basically it's a simple component into which I inject an item which has a name property. The name property really has a value, which I can see as the line <span>You selected {{item.name}},</span> works fine.

I don't know, why it doesn't work. From my understanding everything should be correct. I compared with the angular repo on github, the unit tests, etc.

These are the things I checked and I believe are ok:

  • NgSwitch is imported and injected via directives
  • syntax is correct
  • item really is available (but maybe not in the context of NgSwitch?)

Just to be really sure, I also tried something trivial like following template (switching over a hard-coded string or a number):

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

And this doesn't work either, so it must be something really basic which I am doing wrong.. I'm afraid I can't find any examples or code snippets on the internet. Any help would be appreciated, thanks in advance.


回答1:


You need to import NgSwitchWhen and NgSwitchDefault, add these to the import statements



来源:https://stackoverflow.com/questions/30724410/ng-switch-in-angular2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!