问题
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";
}
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)
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