在[(ngModel)]中绑定私有属性 [英] Binding private property in [(ngModel)]

查看:91
本文介绍了在[(ngModel)]中绑定私有属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Angular 4中绑定private属性?

How to bind private property in Angular 4?

export class newItem{
  private id: number;
  private description: string;
  private insertDate: any;

  get getId() : number {
    return this.id;
  }
  set setId(name : number) {
    this.id = name;
  }
  get getDescription() : string {
    return this.description;
  }
  set setDescription(description : string) {
    this.description = description;
  }
  get getInsertDate() : string {
    return this.insertDate;
  }
  set setInsertDate(insertDate : string) {
    this.insertDate = insertDate;
  }

这里

它抛出Cannot assign to 'getInsertDate' because it is a constant or a read-only property.

推荐答案

只需直接绑定属性:

此柱塞中的演示

模板:

<input [(ngModel)]="testVar" #textBox type="text"> 
<p>This is the value of testVar : {{testVar}}</p>

组件:

 export class MyComponent {
     private testVar: string = "Test this";
 }


  1. 如果要进行双重绑定并使用getter和setter,则您的get和set必须具有相同的名称(模板中使用的名称)

  1. if you want double-binding and use getters and setters, then your get and set must have the same name (the name used in the template)

属性无需在组件中公开即可允许与ngModel进行数据绑定.他们可以完全是私人的.

properties don't need to be public in component to allow data binding with ngModel. They can perfectly be private.

,正如在其他答案中已经说过的那样,在您的情况下您根本不需要吸气剂和塞特剂!.

and as already said in other answers, in your situation you don't need getter and setters at all!.

为了自己的头脑,最好避免不必要的代码!

Best to avoid unnecessary code, for your own mind sanity !

如果您担心封装,请不要:将模板视为组件的一部分.模板使用组件私有字段是绝对可以的(除非您愿意,否则无需通过获取/设置访问器)

If you are worried about encapsulation, don't be : think of your template as part of your component. It's absolutely ok for the template to use the components private fields (and without going through get/set accessors, unless you want it)

不幸的是,绑定变量应该是公共的.

The bound variable should be public, unfortunately.

这篇关于在[(ngModel)]中绑定私有属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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