如何在 angular 中的数据类型上使用 ngSwitch?

How to use ngSwitch on datatype in angular?

我当时在 angular2 工作,很想知道我是否可以使用 ngSwitch 在变量为特定 datatype.i.e 时加载 <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 标签? 如果没有,有什么解决方法吗?

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

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 版本。

另一种方法是使用 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>