从前两天开始,我一直在尝试让ngswitch在angular 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 { }

然后将此共享模块导入到主模块中。
小姐在哪里?

最佳答案

https://angular.io/docs/ts/latest/api/common/index/NgSwitch-directive.html
ngSwitch不能在<template>元素上,只能在<div>这样的实际元素上
只有ngSwitchCase可以应用于<template>元素

<template [ngSwitchCase]="match_expression_3">

或者,因为finalng-container可以用更常见的语法代替<template>
<ng-container *ngSwitchCase="match_expression_3">

关于angular - 如何在angular2中使用ngSwitch,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41085109/

10-09 21:29