What is the most effective method for responding to property changes within a component? I am seeking a solution that will trigger a specific function every time a property in a component is altered. Consider the following example with a single component:
@Component({selector: 'component', template: '{{name}} {{number}}'})
class singleComp {
name: string = 'Old';
number: number = 1;
changeProperties() {
this.name = 'New';
this.number = 2;
}
changesDetected() {
console.log('Changes detected');
}
}
In the scenario presented above, the singleComp has two properties - name
and number
. While calling changesDetected()
from changeProperties()
could be a solution, it might not be practical if there are multiple methods affecting the component's properties. Manually adding changesDetected()
at the end of each property-modifying method could result in multiple calls from various methods.
I have attempted to detect changes using OnChanges
and AfterContentChecked
, but these approaches do not fully capture all internal property modifications within a component.
In simple terms, I am looking for a way to automatically execute the changesDetected()
function whenever any internal property of the component is modified.
edit
While it is possible that ngDoCheck
can identify internal changes, implementing it may also lead to tracking changes in external components, making it less suitable for monitoring changes strictly at a component level.