如何在angular2中使用ngSwitch

Abh*_*ash 13 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>
Run Code Online (Sandbox Code Playgroud)

零件 -

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'
    }
  }

}
Run Code Online (Sandbox Code Playgroud)

以下是我的模块配置 -

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 { }
Run Code Online (Sandbox Code Playgroud)

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

小姐在哪里?

Gün*_*uer 26

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

ngSwitch不能在一个<template>元素上,只能在真实的元素上<div>

只能ngSwitchCase应用于<template>元素

<template [ngSwitchCase]="match_expression_3">
Run Code Online (Sandbox Code Playgroud)

或者,因为ng-container可以使用final 而不是<template>更常见的语法:

<ng-container *ngSwitchCase="match_expression_3">
Run Code Online (Sandbox Code Playgroud)