Reputation: 1121
What is the best approach of reacting to property changes at a component level? What I am looking for is a way to trigger a method each time one of the properties of a component changes. Here's 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 example above, the singleComp has two properties name
and number
. This is a simple example. Calling changesDetected()
from changeProperties()
is not an option as the component may have multiple methods modifying the component's properties. I don't want to call changesDetected()
at the end of each method that modifies a property because that will mean multiple calls from multiple methods.
I have tried to detect changes using OnChanges
and AfterContentChecked
, but none of them really work. Those methods detect changes on the @input
properties but not detect the changes of "native" properties inside a component.
Shortly described, I am looking for a way to fire the changesDetected()
each time an internal property of the component is modified.
edit
It is true that ngDoCheck
detects internal changes. However, once implemented it will also detect changes on external components and it is not really useful at a component level.
Upvotes: 2
Views: 2997
Reputation: 1901
You should use EventEmitter or this use case.
hat is the best approach of reacting to property changes at a component level? What I am looking for is a way to trigger a method each time one of the properties of a component changes. Here's a single component:
@Component({selector: 'component', template: '{{name}} {{number}}'})
class singleComp {
name: string = 'Old';
number: number = 1;
private propertiesChanged: EventEmitter<any> = new EventEmitter();
private _score: number;
get score():boolean {
return this._score;
}
set score(s:number) {
this._score = s;
this.propertiesChanged.emit(s);
}
constructor() {
this.propertiesChanged.subscrive(() => this.changesDetected());
}
changeProperties() {
this.name = 'New';
this.number = 2;
this.propertiesChanged.emit({}); // you can pass any object here, chanegd properties as well.
}
changesDetected() {
console.log('Changes detected');
}
}
You can also emit change event in the setter of these properties, choose whatever makes more sense in your use case. see the score property for instance
Upvotes: 1