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

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

问题描述

如果在组件类上声明了一个变量private,我是否可以在该组件的模板中访问它?

@Component({选择器:'我的应用',模板:`<div><h2>{{title}}</h2><h2>你好{{userName}}</h2>//我得到这个名字

`,})出口类应用{public title = 'Angular 2';private userName = "测试名称";//声明为私有}

解决方案

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

虽然我喜欢 drewmoore 的答案,并且在其中看到了完美的概念逻辑,但在实现上却是错误的.模板不存在于组件类中,而是存在于组件类之外.看看 这个 repo 以获得证明.

它起作用的唯一原因是因为 TypeScript 的 private 关键字并没有真正将成员设为私有.即时编译发生在运行时的浏览器中,并且 JS 没有任何私有成员的概念(还没有?).感谢 Sander Elias 让我走上正轨.

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

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.

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.

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.

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天全站免登陆