Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
370 views
in Technique[技术] by (71.8m points)

javascript - How to check type of variable in ngIf in Angular2

I'm learning Angular2. I have a component with a variable which is an object. I'm iterating over the fields of the object, and acording to the type of data of that position, I need to render a different compoenent. In this case, I want tu render that label if the typeof that position is a number how ever this is not working

<div>
  <div *ngIf='obj'>
    <label *ngFor="let key of keys; let i = index">
      <label class='key'>{{key}}:</label>
      <label class='number' *ngIf='typeof obj[key] === "number"'>
      <!-- label class='number' *ngIf='obj[key] | typeof === "number"' -->
        {{ obj[key] }}
      </label>
    </label>
  </div>
</div>

Any ideas?

I have also created a pipe to get the typeof which work when I print the value, but not inside the *ngIf

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Globals like window, typeof, enums, or static methods are not available within a template. Only members of the component class and typescript language constructs are available.

You can add a helper method to your component like

isNumber(val): boolean { return typeof val === 'number'; }

and use it like

<label class='number' *ngIf='isNumber(obj[key])'>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...