Reputation: 712
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.
Upvotes: 2
Views: 3328
Reputation: 23174
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";
}
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)
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.
Upvotes: 1
Reputation: 712
The answer is to change it to:
private _id: number;
get id() : number {
return this.id;
}
set id(name : number) {
this.id = name;
}
Upvotes: 1