angular - 如何在 angular2 中使用 ngSwitch

标签 angular

自从过去两天以来,我一直在尝试让 ngSwitchAngular 2.1.0 中工作。但似乎不可能让它发挥作用。

我总是得到:

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

然后这个共享模块被导入到主模块中。

小姐在哪里?

最佳答案

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">

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

相关文章:

javascript - ngbuild根据环境改变占位符

angular - NPM 脚本 'start' 退出时没有指示 Angular CLI 正在监听请求

angular - Tslint - 类型简单推断 - 为什么在此处包含类型是不好的做法?

angular - 是否可以从 formcontrol 中获取 minlength 值?

java - 在 Spring Boot 应用程序中通过 Jersey 资源方法提供静态内容

javascript - 从本地文件到 Angular 5 中的 Typescript 数组的 JSON 数组

Angular (4, 5, 6, 7) - ngIf 上滑入滑出动画的简单示例

Ionic 中的 Angular 2 react 形式复选框验证

angular - http get 请求返回未定义

angular 6 "ExpressionChangedAfterItHasBeenCheckedError" react 形式动态表单验证添加和删除