Binding private property in [(ngModel)]

陌路散爱 提交于 2020-06-27 16:57:10

问题


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;
  }

Here

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


回答1:


The answer is to change it to:

private _id: number;
  get id() : number {
    return this.id;
  }
  set id(name : number) {
    this.id = name;
  }



回答2:


Just bind the property directly :

Demo in this Plunker

Template :

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

Component :

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

  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)

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

  3. 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)

If you are using Ahead Of Time (AOT) compilation

The bound variable should be public, unfortunately.




回答3:


"How to bind private property in Angular 4?"

There is no way to bind private variables to template (using [(ngModel)] in your case). You should use public variables.



来源:https://stackoverflow.com/questions/46734156/binding-private-property-in-ngmodel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!