As I delved into the Angular2 documentation, a specific example caught my eye in the Hierarchical Dependency Injectors chapter. It introduced me to the Restore service, which enables save/cancel functionality for editing.
The code for this service is as follows:
export class RestoreService<T> {
originalItem: T;
currentItem: T;
setItem (item: T) {
this.originalItem = item;
this.currentItem = this.clone(item);
}
getItem () :T {
return this.currentItem;
}
restoreItem () :T {
this.currentItem = this.originalItem;
return this.getItem();
}
clone (item: T) :T {
return JSON.parse(JSON.stringify(item));
}
}
Excited by this discovery, I decided to try it out myself! Firstly, I initialized the values like this:
ngAfterContentInit(){
this.metadata = {
languages: this.selected_languages,
countries: this.selected_countries,
international: false
}
}
set metadata(metadata: CvMetadata){
this._restoreService.setItem(metadata);
}
get metadata(): CvMetadata{
return this._restoreService.getItem();
}
Next, I proceeded to change the values of the metadata properties using ngModel, such as
[(ngModel)]="metadata.languages[0]"
The question:
To my surprise, when I update the value of the metadata property with ngModel, only the currentItem changes while the originalItem remains unaffected. This left me puzzled as I initially expected ngModel to trigger the setter method for setting the metadata properties. However, the setter is invoked only once during the initial data setup. How does ngModel differentiate between changing the currentItem and not touching the originalItem? Is this some form of magic at play?
I know it's quite a specific query, but alas, you are the only ones I have to turn to for an explanation!
Thank you!