如何在angular2中使用ngSwitch [英] How to use ngSwitch in angular2

查看:434
本文介绍了如何在angular2中使用ngSwitch的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

自最近两天以来,我一直在尝试让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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆