如何在angular2中使用ngSwitch [英] How to use ngSwitch in angular2
问题描述
自最近两天以来,我一直在尝试让ngSwitch
在 Angular 2.1.0 中工作.但是似乎无法使其正常工作.
Since last two days I am trying to get ngSwitch
to work in Angular 2.1.0. But it seems impossible to get it work.
我总是得到:
没有NgSwitch的提供程序
No provider for NgSwitch
下面是我的代码:
模板:
<template [ngSwitch]="buttonSelector">
<a class="btn" [ngClass]="buttonSizeClass" *ngSwitchCase="'link'" href="#">
<span class="btn__text">
<ng-content></ng-content>
</span>
</a>
</template>
组件:
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'
}
}
}
以下是我的模块配置:
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 shared module is then imported in the main module.
小姐在哪里?
推荐答案
https://angular.io/docs/ts/latest/api/common/index/NgSwitch-directive.html
ngSwitch
不能在<template>
元素上,只能在像<div>
ngSwitch
can't be on a <template>
element, only on real elements like <div>
仅ngSwitchCase
可以应用于<template>
元素
<template [ngSwitchCase]="match_expression_3">
或者,由于可以使用最终的ng-container
而不是<template>
,因此具有更通用的语法:
Alternatively since final ng-container
can be used instead of <template>
with the more common syntax:
<ng-container *ngSwitchCase="match_expression_3">
这篇关于如何在angular2中使用ngSwitch的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!