I have seen similar questions on this issue but non of the answers worked for me. I have a boolean value that change whenever an async task has been completed, but it's strange that ngonchages does not fire anytime it changes. Below is my code:
import {
Component,
OnChanges,
SimpleChange
} from '@angular/core';
export class HomePage implements OnChanges {
isLoaded: boolean;
constructor() {
this.isLoaded = false;
this.loadData();
}
loadData() {
setTimeout(() => {
this.isLoaded = true;
console.log(this.isLoaded);
}, 3000);
}
ngOnChanges(changes) {
console.log("There has been a change ", changes); //this is not firing
}
}
During change detection, when Angular checks components' input properties for change, it uses (essentially) === for dirty checking. For arrays, this means the array references (only) are dirty checked. Since the rawLapsData array reference isn't changing, ngOnChanges() will not be called.
Use ngOnChanges whenever you want to detect changes from a variable decorated by @Input. Remember that only changes from the parent component will trigger this function.
The ngOnChnages is a life cycle hook, which angular fires when it detects changes to data-bound input property. This method receives a SimpeChanges object, which contains the current and previous property values. The child Component decorates the property using the @Input decorator.
ngOnChanges() ( OnChanges ) is called when a value bound to an input has changed so you can run custom code when an input has changed. ngDoCheck() ( DoCheck ) is called when change detection runs so you can implement your custom change detection action.
ngOnChanges
is a lifecycle callback of Angulars change detection mechanism and it is called when an @Input()
is changed by Angulars data binding
When you have
@Input() isLoaded: boolean;
and
<home-page [isLoaded]="someValue">
and someValue
in the parent component is changed, then change detection updates isLoaded
and calls ngOnChanges()
.
For your case the simplest solution is probably using a getter instead of a property:
_isLoaded: boolean;
set isLoaded(value:bool) {
this._isLoaded = value;
this.doSomething(value)
}
get isLoaded() {
return this._isLoaded;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With