Javascript 如何在Angular2中检查ngIf中的变量类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37511055/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 20:24:25  来源:igfitidea点击:

How to check type of variable in ngIf in Angular2

javascriptangular

提问by Pablo

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 labelif the typeofthat position is a numberhow ever this is not working

我正在学习 Angular2。我有一个带有变量的组件,它是一个对象。我正在迭代对象的字段,并根据该位置的数据类型,我需要呈现不同的组件。在这种情况下,我想要你渲染,label如果typeof那个位置是一个number如何这不起作用

<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 typeofwhich work when I print the value, but not inside the *ngIf

我还创建了一个管道来typeof在我打印值时获得哪个工作,但不在 *ngIf 内

回答by Günter Z?chbauer

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.

windowtypeof、 枚举或静态方法这样的全局变量在模板中不可用。只有组件类和打字稿语言结构的成员可用。

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])'>

回答by zurfyx

Alternatively, you can compare the constructor name.

或者,您可以比较构造函数名称。

{{ foo.constructor.name === 'FooClass' }}

Detailed info about this here.

这里有关于这方面的详细信息。

回答by Owen

I just tried this and found it won't work in production because function names are shortened. It's safer to use something like:

我刚刚试过这个,发现它在生产中不起作用,因为函数名称被缩短了。使用类似的东西更安全:

foo instanceof FooClass

But note that you have to do this in the component/directive because instanceOfis not available in templating:

但请注意,您必须在组件/指令中执行此操作,因为instanceOf在模板中不可用:

// In your component
isFoo(candidate){
    return candidate instanceof FooClass;
}

// in your template
{{isFoo(maybeFoo)}}

回答by Armen Stepanyan

You can create simple pipe which will receive current item and return item type.

您可以创建简单的管道,它将接收当前项目并返回项目类型。

   import { Pipe, PipeTransform } from '@angular/core';

    @Pipe({
      name: 'typeof'
    })
    export class TypeofPipe implements PipeTransform {

      transform(value: any): any {
        console.log("Pipe works ",typeof value);
        return typeof value;
      }

    }

Now you can use typeofpipe in html like this

现在你可以像这样在 html 中使用 typeofpipe

*ngIf = (item | typeof) === 'number'"

And be careful in using function call in your html as mentioned above. It preferred to use pipe instead of function call. Here is Stackblitzexample. In first case function call will triggered on any change detection (example on clicking on buttons).

如上所述,在 html 中使用函数调用时要小心。它更喜欢使用管道而不是函数调用。这是Stackblitz示例。在第一种情况下,函数调用将在任何更改检测时触发(例如单击按钮)。

回答by tobek

This is a bit of a hack, but if you need to do this in a lot of places and don't want the cruft of passing some isNumberfunction around, there's another option that can work if you use it carefully.

这是一个小技巧,但是如果您需要在很多地方执行此操作并且不想繁琐地传递某些isNumber函数,那么如果您谨慎使用,还有另一个选项可以工作。

You can check for the existence of properties or methods that exist on the prototypeof the object or type you're looking for. For example, all numbers have a toExponentialfunction, so:

您可以检查prototype您正在查找的对象或类型上是否存在属性或方法。例如,所有数字都有一个toExponential函数,所以:

<label class='number' *ngIf='obj[key] && obj[key].toExponential'>

For functions you could look for call, for strings you could look for toLowerCase, for arrays you could look for concat, etc.

对于可以查找的函数call,对于可以查找的字符串,对于可以查找toLowerCase的数组concat,等等。

This approach isn't foolproof at all, since you could have an objectthat happens to possess a property with the same name that you're checking (though if the property you're checking is all you need, then we're basically duck typing), but if you know that the value you have is a primitive you're in good shape, since you can't assign properties on primitives (here is some interesting readingon that topic).

这种方法根本不是万无一失的,因为您可能有一个object碰巧拥有与您正在检查的名称相同的属性(尽管如果您正在检查的属性就是您所需要的,那么我们基本上是鸭子打字),但是如果您知道您拥有的值是一个基元,那么您就处于良好状态,因为您无法为基元分配属性(这里有一些关于该主题的有趣阅读)。

Disclaimer: I don't really trust that this is a good idea and may not be very maintainable or portable, but if you just need something quick for a prototype or a very limited use case, this is a reasonable tool to have in your belt.

免责声明:我真的不相信这是一个好主意,可能不是很容易维护或便携,但如果你只是需要一些快速的原型或非常有限的用例,这是一个合理的工具.