ng-switch in Angular2

PzYon picture PzYon · Jun 9, 2015 · Viewed 13.2k times · Source

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.

Answer

unobf picture unobf · Jun 10, 2015

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