Angular2-可以在模板中访问私有变量吗? [英] Angular2 - should private variables be accessible in the template?

查看:121
本文介绍了Angular2-可以在模板中访问私有变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果在组件类上将变量声明为private,我是否应该能够在该组件的模板中访问它?

If a variable is declared private on a component class, should I be able to access it in the template of that component?

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>{{title}}</h2>
      <h2>Hello {{userName}}</h2> // I am getting this name
    </div>
  `,
})
export class App {
  public title = 'Angular 2';
  private userName = "Test Name"; //declared as private
}

推荐答案

不,您不应该在模板中使用私有变量.

No, you shouldn't be using private variables in your templates.

虽然我喜欢 drewmoore的答案,并且在其中看到了完美的概念逻辑,但在实现上是错误的.模板不存在于组件类中,而是在它们之外.看看此存储库作为证据.

While I like the drewmoore's answer and see perfect conceptual logic in it, implementationwise it's wrong. Templates do not exist within component classes, but outside of them. Take a look at this repo for the proof.

它起作用的唯一原因是因为TypeScript的private关键字并未真正使成员私有.即时编译在运行时在浏览器中进行,并且JS没有私有成员的概念(还可以吗?).致谢 Sander Elias 使我走上了正确的道路.

The only reason why it works is because TypeScript's private keyword doesn't really make member private. Just-in-Time compilation happens in a browser at runtime and JS doesn't have any concept of private members (yet?). Credit goes to Sander Elias for putting me on the right track.

使用ngc和Ahead-of-Time编译,如果尝试从模板访问组件的私有成员,则会出现错误.克隆演示仓库,将MyComponent成员的可见性更改为private,运行ngc时会出现编译错误.这也是 answer 专门针对提前编译的问题.

With ngc and Ahead-of-Time compilation, you'll get errors if you try accessing private members of the component from template. Clone demonstration repo, change MyComponent members' visibility to private and you will get compilation errors, when running ngc. Here is also answer specific for Ahead-of-Time compilation.

这篇关于Angular2-可以在模板中访问私有变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆