问题描述
我在这个问题上也看到了类似的问题,但是没有一个答案对我有用.我有一个布尔值,它会在异步任务完成时发生更改,但是奇怪的是,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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!