Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it necessary to write Object=Object in Component to get Object.keys in Angular?

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.

  1. I don't understand what the philosophy behind this is.
  2. How do other expressions and statements in curly braces work in an Angular template?
like image 992
shyammakwana.me Avatar asked Mar 16 '19 06:03

shyammakwana.me


1 Answers

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.

like image 124
Fullstack Guy Avatar answered Oct 24 '22 21:10

Fullstack Guy