如何在Angular2中检查ngIf中的变量类型 [英] How to check type of variable in ngIf in Angular2
问题描述
我正在学习Angular2。我有一个带有变量的组件,它是一个对象。
我正在迭代对象的字段,并根据该位置的数据类型,我需要渲染一个不同的组件。
在这种情况下,如果 typeof
该位置是<$ c,我想要tu渲染 label
$ c>数字如何无法使用
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>
任何想法?
我也有创建了一个管道,以获取 typeof
,当我打印该值时,该管道工作,但不在* ngIf
I have also created a pipe to get the typeof
which work when I print the value, but not inside the *ngIf
推荐答案
在窗口
, typeof
,枚举或静态方法等全局内不可用一个模板。只有组件类和打字稿语言结构的成员可用。
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) { return typeof val === 'number'; }
并使用它
<label class='number' *ngIf='isNumber(obj[key])'>
这篇关于如何在Angular2中检查ngIf中的变量类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!