Reputation: 113
I am updating a component property, but ngOnChanges is not being called. Please see the linked StackBlitz to see the problem reproduced and everything I have tried so far:
https://stackblitz.com/edit/angular-becgjq
Edit: correct link to view code
Relevant code
ngOnInit() {
const testButton1 = document.getElementById('test-button1');
testButton1.addEventListener('click', function() {
console.log('about to set this.value');
console.log(this.value);
this.value = 'value set by button 1';
}.bind(this));
const testButton2 = document.getElementById('test-button2');
testButton2.addEventListener('click', this.testButtonCallback2(this), false);
const testButton3 = document.getElementById('test-button3');
testButton3.addEventListener('click', this.testButtonCallback3.bind(this), false);
}
ngOnChanges() {
console.log('ngOnChanges was called');
}
testButtonCallback2(outerThis) {
return function() {
console.log('about to set this.value');
console.log(outerThis.value);
outerThis.value = 'value is set by callback2';
}
}
testButtonCallback3() {
console.log('about to set this.value');
console.log(this.value);
this.value = 'value is set by callback3';
this.changeDetectorRef.detectChanges();
}
Upvotes: 0
Views: 2667
Reputation: 60557
Have a look at the official docs.
Angular calls its ngOnChanges() method whenever it detects changes to input properties of the component (or directive).
You don't have any inputs in your component so ngOnChanges
will never be called.
Also, you should actually use the methods Angular provides. I can only recommend you to follow the tutorial. For example, you should not add event listeners with addEventListener
but with (click)
in your template like this:
<button (click)="testButtonCallback()">Test Button</button>
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Upvotes: 2