Update: I ended up using properties that access the model and call the external change tracking inside the setters.
get text(): string {
return model.text
}
set text(value: string) {
// <-- Call the change tracker here
this.model.text = value;
}
Original Question
I have a system written using AngularJS where I needed to externally track the changes of each model (track dirties). In AngularJS it was a simple as adding watchers for every model's property (including changes in properties of elements inside arrays). Note: the models are used as the data for the UI components.
The data flow was like this:
- SPA requests data from server.
- Server gets the data.
- A watcher is added to every model's property before returning the data.
- Watched models are returned to the SPA.
Here's the main code that watched for changes:
public attachModel(obj : any, id : string, scope: ng.IScope, propertyName: string) {
var idObj = obj.Id;
this.attachedObjs[obj.Id] = obj; // Just keeping control of tracked objs
var that = this;
// The 'id' used in the watch is unique for the tracked property
scope.$watch(id, function () {
that.changeTracker(idObj, propertyName); // Calls dirty tracking
});
}
Every time a property was changed in any of the models, an event was triggered and the model's property was marked as dirty in the external change control.
I am trying to find a replacement for this functionality in the new Angular, but I feel like I am not in the right path, the only options that I currently have are:
- Use something like RxJS
Do
method to call the dirty tracking. - Use ngrx Observables and add @Effects to trigger the dirty tracking.
One important thing is that in AngularJS I had a single point where all models were added to dirty tracking control.
Is there any way to achieve this in Angular? Or a way to intercept Angular's Change Detection to trigger the dirty tracking?
Note: I found a question that somehow I missed during my initial search, is there any way to achieve this outside an ngForm? How to watch for form changes in Angular 2?