In my Angular template I need the key count of an Object. I was writing {{ Object.keys(myObj).length }}
in the template file. But it throws an error: ERROR TypeError: Cannot read property 'keys' of undefined
.
Then from the internet I got a suggestion, so I wrote Object = Object
in my component and it worked.
The template expression context is usually limited to the component instance itself. So when you interpolate a variable inside {{}}
it will essentially look for a matching property of the underlying component instance or a template reference variable.
When you do Object = Object
in a component, you are actually creating a property Object
of the component which refers to the global Object
which the component has a reference to.
But the same is not possible inside a template expression, it does not have any access to global properties except undefined
.
This part of the docs explains this:
Template expressions cannot refer to anything in the global namespace, except undefined. They can't refer to window or document. Additionally, they can't call console.log() or Math.max() and they are restricted to referencing members of the expression context.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With