如何在angular2中使用ngSwitch

时间:2016-12-11 10:17:29

标签: angular

自从过去两天以来,我试图让ngSwitch在角度2.1.0中工作。但似乎不可能让它发挥作用。

我总是得不到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 { }

然后将此共享模块导入主模块。

小姐在哪儿?

3 个答案:

答案 0 :(得分:20)

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

ngSwitch无法访问<template>元素,仅适用于<div>等真实元素

只有ngSwitchCase可以应用于<template>元素

<template [ngSwitchCase]="match_expression_3">

或者,因为可以使用最终ng-container代替<template>,使用更常见的语法:

<ng-container *ngSwitchCase="match_expression_3">

答案 1 :(得分:2)

您需要从ngSwitch

导入angular2/common
import {NgSwitch} from 'angular2/common'

答案 2 :(得分:0)

也面临同样的问题确保

  1. NgSwitch不应没有模板,而应位于Div等真实元素上
  2. *ngSwitchCase="expression"应该嵌套在NgSwitch元素内