Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is ngOnchanges not firing when a boolean value changed in angularjs 2

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
    }
}
like image 740
Mark Adesina Omoniyi Avatar asked Sep 28 '16 07:09

Mark Adesina Omoniyi


People also ask

Why ngOnChanges is not getting called?

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.

Does detect changes trigger ngOnChanges?

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.

How does ngOnChanges work in Angular?

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.

What is difference between ngOnChanges and ngDoCheck?

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.


1 Answers

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;
}
like image 174
Günter Zöchbauer Avatar answered Sep 20 '22 13:09

Günter Zöchbauer