How to use ngSwitch on datatype in angular?

醉酒当歌 提交于 2019-12-24 05:44:08

问题


I was working in angular2 and was curious to know whether I could use ngSwitch to load <div> tag when variable is of certain datatype.i.e. something like this:

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

is this possible to load the div tag when variable is of certain datatype? if not, any workaround for this?


回答1:


An alternative would be to use 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>



回答2:


Yes, you can do it but now directly in template. Just create a method in controller to check for a type:

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


Please update your Angular to RC version first.



来源:https://stackoverflow.com/questions/38013862/how-to-use-ngswitch-on-datatype-in-angular

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!