最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Why is ngOnchanges not firing when a boolean value changed in angularjs 2 - Stack Overflow

programmeradmin1浏览0评论

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 pleted, 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
    }
}

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 pleted, 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
    }
}
Share Improve this question edited Sep 28, 2016 at 8:34 Krupesh Kotecha 2,4123 gold badges22 silver badges40 bronze badges asked Sep 28, 2016 at 7:54 Mark Adesina OmoniyiMark Adesina Omoniyi 4496 silver badges21 bronze badges 1
  • Either isLoaded should be there on view bindings/@input property.. – Pankaj Parkar Commented Sep 28, 2016 at 7:57
Add a ment  | 

2 Answers 2

Reset to default 6

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 ponent 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;
}

Property treated as input (part of checking changes) should be marked with @Input

@Input()
isLoaded: boolean;
发布评论

评论列表(0)

  1. 暂无评论