【问题标题】:How to use ngSwitch on datatype in angular?如何在角度数据类型上使用 ngSwitch?
【发布时间】:2016-10-27 02:25:04
【问题描述】:

我在 angular2 中工作,很想知道当变量是特定数据类型时是否可以使用 ngSwitch 加载 <div> 标签。即 像这样:

 <div [ng-switch]="value">
  <p *ng-switch-when="isObject(value)">This is Object</p>
  <p *ng-switch-when="isArray(value)">This is Array</p>
  <p *ng-switch-when="isBoolean(value)">This is Boolean</p>
  <p *ng-switch-when="isNumber(value)">This is Number</p>
  <p *ng-switch-default>This is Simple Text !</p>
</div>

当变量是某种数据类型时,这是否可以加载div 标记? 如果没有,有什么解决方法吗?

【问题讨论】:

  • 为什么不使用 ngIf?

标签: angular typescript instanceof typeof ng-switch


【解决方案1】:

另一种方法是使用ngIf:

  <p *ngIf="isObject(value)">This is Object</p>
  <p *ngIf="isArray(value)">This is Array</p>
  <p *ngIf="isBoolean(value)">This is Boolean</p>
  <p *ngIf="isNumber(value)">This is Number</p>
  <p *ngIf="!isObject(value) || !isArray(value) || !isBoolean(value) || !isNumber(value)">This is Simple Text !</p>

【讨论】:

  • 所以 ngIf 响应它发现的第一个 false ?有趣的。 ||将评估每个陈述寻找一个真实的通常不会吗?这意味着代码应该输出一团糟。
  • 反之,它显示所有评估为true 值的p 标记
【解决方案2】:

是的,您可以这样做,但现在直接在模板中。只需在控制器中创建一个方法来检查类型:

import {Component} from '@angular/core'

@Component({
  selector: 'my-app',
  providers: [],
  template: `
    <div>
      <div [ngSwitch]="checkType(name)">
        <p *ngSwitchCase="'string'">is a string!</p>
        <p *ngSwitchDefault>default</p>
      </div>
    </div>
  `,
  directives: []
})
export class App {
  constructor() {
    this.name = 'Angular2 (Release Candidate!)'
  }

  checkType(value) {
    return typeof value
  }
}

Working Plunker


请先将您的 Angular 更新为 RC 版本。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-12
    • 2017-01-17
    • 1970-01-01
    • 1970-01-01
    • 2020-07-07
    • 1970-01-01
    • 2013-10-24
    • 2019-03-08
    相关资源
    最近更新 更多