javascript - 为什么要在Component中写Object=Object才能在Angular中获取Object.keys?

标签 javascript angular angular6

在我的 Angular 模板中,我需要对象的键数。我在模板文件中写了 {{ Object.keys(myObj).length }}。但它会引发错误:ERROR TypeError: Cannot read property 'keys' of undefined

然后我从互联网上得到了一个建议,所以我在我的组件中写了 Object = Object 并且它起作用了。

  1. 我不明白这背后的哲学是什么。
  2. 花括号中的其他表达式和语句在 Angular 模板中如何工作?

最佳答案

模板表达式上下文通常仅限于组件实例本身。因此,当您在 {{}} 中插入一个变量时,它实际上会查找底层组件实例或模板引用变量的匹配属性。

当您在组件中执行 Object = Object 时,您实际上是在创建组件的属性 Object,它引用全局 Object组件引用了哪个。

但是在模板表达式中是不可能的,它不能访问全局属性,除了undefined

这部分docs解释这个:

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.

关于javascript - 为什么要在Component中写Object=Object才能在Angular中获取Object.keys?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55194167/

相关文章:

javascript - 在 Express-Sequelize MySql 中创建 2 个模型之间的关联

Angular 7 : Trigger valuechanges on addControl, 如果值存在

javascript - 如何在 Angular 中使用 ES6 字符串模板为变量分配粗体(样式)?

javascript - 如何在单击按钮时验证输入不保存 0 或小于 0?

javascript - 刷新div内的php脚本

javascript - window.location 重定向到 IE11 和 mozilla 中的主页

javascript - 如何在同一页面上使用 2 个 ng-repeat 指令在 Angular 中隔离/封装 $index ?

JavaScript 将字符串插入对象迭代中

angular6 - 非法状态 : Could not load the summary for directive AppComponent

javascript - 如果动态分配验证模式,setValidators 不起作用