Raza Ellahi
Raza Ellahi

Reputation: 409

check type of variable in HTML

In my view class i am rendering some data, i am getting a variable and i want to check that if the type of variable is Boolean than i want to show a switch button for it, but if the type is number then i want to show a slider for it.

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

Upvotes: 6

Views: 10726

Answers (2)

Lia
Lia

Reputation: 11982

Write a simple typeOf method to check the type:

ts:

typeOf(value) {
  return typeof value;
}

And then use it in your template:

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

Here's a Working Sample StackBlitz for your ref.

Upvotes: 10

HPeter
HPeter

Reputation: 39

You can use typeof, and put it into an ngIf

typeof i === "number"

and

typeof i === "boolean"

Upvotes: -3

Related Questions