Reputation: 93
I'm using Angular 2 and I'm using some getter's and setter's to communicate between components. I'm running into problems where the getter and setter functions are run a lot of times, even though they don't depend on anything. Am I doing something wrong?
for the getter function I just have this code:
private get SomeData(): string {
console.log("Getter called");
return "some string";
}
the setter code is:
@Input()
public set SomeData(newData: string) {
console.log("Setter called");
}
The binding is:
<child-comp [SomeData]="SomeData"></child-comp>
The console is showing Getter called, Setter called, then after that it print some 20 Getter called lines. Why are these called?
Upvotes: 3
Views: 2294
Reputation: 657741
The problem is caused by
private get SomeData(): string {
console.log("Getter called");
return "some string";
}
because it returns a new string instance every time when change detection checks whether the value has changed
If you change the code to
private someData:string = "some string";
private get SomeData(): string {
console.log("Getter called");
return this.someData;
}
then the same string instance will returned every time, Angular recognizes it as unchanged and the setter won't be called unless someData
has changed.
Upvotes: 6