本文介绍了如何停止在ngOnInit()之前调用的ngOnChanges的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我的有角度的应用程序中,我想到了一种情况,仅当输入绑定到更改时才应调用ngOnchanges.因此,有没有办法在ngOnInit之前停止ngOnChanges的执行.有没有办法做到这一点.预先感谢.
In my angular application, i came up with a situation where ngOnchanges should only be called when the inputs are bound to changes. so, is there a way to stop the execution of ngOnChanges before ngOnInit. Is there a way to accomplish this.Thanks in Advance.
推荐答案
您不能阻止此行为,但是可以:
You cannot prevent this behavior, but you can:
class Foo implements OnChanges,OnInit,OnDestroy{
onChanges = new Subject<SimpleChanges>();
ngOnInit(){
this.onChanges.subscribe((data:SimpleChanges)=>{
// only when inited
});
}
ngOnDestroy(){
this.onChanges.complete();
}
ngOnChanges(changes:SimpleChanges){
this.onChanges.next(changes);
}
}
使用布尔属性:
class Foo implements OnChanges,OnInit{
initialized=false;
ngOnInit(){
// do stuff
this.initialized = true;
}
ngOnChanges(changes:SimpleChanges){
if(this.initialized){
// do stuff when ngOnInit has been called
}
}
}
使用SimpleChanges
API
您还可以检查 SimpleChange.isFirstChange()
方法:
Use the SimpleChanges
API
You can also check the SimpleChange.isFirstChange()
method :
class Foo implements OnChanges,OnInit{
@Input()
bar:any;
ngOnInit(){
// do stuff
}
ngOnChanges(changes:SimpleChanges){
if(!changes["bar"].isFirstChange()){
// do stuff if this is not the initialization of "bar"
}
}
}
这篇关于如何停止在ngOnInit()之前调用的ngOnChanges的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!