How to use ngSwitch in angular2

Over the past two days, I have been trying to get ngSwitch to work in angular 2.1.0. But it seems impossible for his work.

I always get No provider for NgSwitch. Below is my code -

Template -

<template [ngSwitch]="buttonSelector"> <a class="btn" [ngClass]="buttonSizeClass" *ngSwitchCase="'link'" href="#"> <span class="btn__text"> <ng-content></ng-content> </span> </a> </template> 

Component -

 import { Component, OnInit, Input } from '@angular/core'; @Component({ selector: 'app-inked-btn', templateUrl: './inked-btn.component.html', styleUrls: ['./inked-btn.component.css'], inputs: ['buttonSize', 'buttonType', "buttonSelector"] }) export class InkedBtnComponent implements OnInit { public buttonSize: string; public buttonType: string; public buttonSelector: string; public buttonSizeClass: any; constructor() { } ngOnInit() { this.buttonSizeClass = { 'btn--lg': this.buttonSize === 'large', 'btn--sm': this.buttonSize === 'small', 'btn--primary': this.buttonType === 'primary' } } } 

Below is my module configuration -

 import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core'; import { CommonModule } from '@angular/common'; import { RouterModule } from '@angular/router'; import { HeaderComponent } from './header/header.component'; import { FooterComponent } from './footer/footer.component'; import { InkedBtnComponent } from './inked-btn/inked-btn.component'; @NgModule({ imports: [ CommonModule, RouterModule ], declarations: [HeaderComponent, FooterComponent, InkedBtnComponent], exports: [HeaderComponent, FooterComponent, InkedBtnComponent], schemas: [CUSTOM_ELEMENTS_SCHEMA] }) export class SharedModule { } 

This common module is then imported into the main module.

Where is the miss?

+7
angular
source share
2 answers

https://angular.io/docs/ts/latest/api/common/index/NgSwitch-directive.html

ngSwitch cannot be in the <template> element, only on real elements such as <div>

Only ngSwitchCase can be applied to <template> elements

 <template [ngSwitchCase]="match_expression_3"> 

Alternatively, since the final ng-container can be used instead of a <template> with the more common syntax:

 <ng-container *ngSwitchCase="match_expression_3"> 
+9
source share

You need to import ngSwitch from angular2/common

 import {NgSwitch} from 'angular2/common' 
+1
source share

All Articles