How to check type of variable in ngIf in Angular2

后端 未结 5 2055
鱼传尺愫
鱼传尺愫 2020-12-14 05:23

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 positio

5条回答
  •  無奈伤痛
    2020-12-14 05:57

    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 isNumber function around, there's another option that can work if you use it carefully.

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

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

    This approach isn't foolproof at all, since you could have an object that 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 reading on that topic).

    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.

提交回复
热议问题