检查HTML中的变量类型

问题描述 投票:0回答:2

在我的视图类我正在渲染一些数据,我得到一个变量,我想检查,如果变量的类型是布尔比我想显示它的开关按钮,但如果类型是数字,那么我想显示一个滑块。

<div *ngFor="let attribute of agent.attributes; let i = index">
      <div class="row">
        <div class="col s2">
          <mat-card>
            <mat-card-header>
              <mat-card-title>{{agent.attributes[i].name}}</mat-card-title>
            </mat-card-header>
            <mat-card-content>
              <div class="center">{{agent.attributes[i].value}}</div>
              <!-- for this value i want to check the type for it, if it is boolean then 
              a switch button should show and if type is number than a slider show be shown -->
            </mat-card-content>
            <mat-card-actions>
              <button mat-button>SAVE</button>
            </mat-card-actions>
          </mat-card>
        </div>
      </div>
    </div>
html angular
2个回答
1
投票

写一个简单的typeOf方法来检查类型:

TS:

typeOf(value) {
  return typeof value;
}

然后在模板中使用它:

<div *ngIf="typeOf(var1) === 'boolean'">switch button</div>
<div *ngIf="typeOf(var1) === 'number'">slider</div>

这是你的参考的Working Sample StackBlitz


0
投票

你可以使用typeof,并把它放入ngIf

typeof i === "number"

typeof i === "boolean"
© www.soinside.com 2019 - 2024. All rights reserved.