在angularjs 2中更改布尔值时,为什么不触发ngOnchanges [英] Why is ngOnchanges not firing when a boolean value changed in angularjs 2

查看:84
本文介绍了在angularjs 2中更改布尔值时,为什么不触发ngOnchanges的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这个问题上也看到了类似的问题,但是没有一个答案对我有用.我有一个布尔值,它会在异步任务完成时发生更改,但是奇怪的是,ngonchages不会在更改时触发.下面是我的代码:

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

推荐答案

ngOnChanges 是Angulars更改检测机制的生命周期回调,在 @Input()>被Angulars数据绑定更改

ngOnChanges is a lifecycle callback of Angulars change detection mechanism and it is called when an @Input() is changed by Angulars data binding

有空

@Input() isLoaded: boolean;

<home-page [isLoaded]="someValue">

更改父组件中的

someValue ,然后更改检测更新 isLoaded 并调用 ngOnChanges().

and someValue in the parent component is changed, then change detection updates isLoaded and calls ngOnChanges().

对于您而言,最简单的解决方案可能是使用getter而不是属性:

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

这篇关于在angularjs 2中更改布尔值时,为什么不触发ngOnchanges的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆