Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to stop ngOnChanges Called before ngOnInit()

Tags:

angular

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.

like image 380
Manush Avatar asked Mar 30 '17 07:03

Manush


People also ask

Does ngOnChanges runs before ngOnInit?

ngOnInit() This is the second lifecycle hook called by Angular, it is called right after the very first ngOnChanges hook is called. It is only called once, it initializes the component, sets and displays component input properties.

Why ngOnChanges is called before ngOnInit?

ngOnChanges gets called before ngOnInit and whenever a component's bound input is changed FROM THE PARENT COMPONENT. Remember that ngOnChanges is specific to bound inputs on the component. This means if you don't have any @Input properties on a child, ngOnChanges will never get called.

How do you use ngOnInit and ngOnChanges together?

ngOnInit() is used to execute any piece of code for only one time (for eg : data fetch on load). ngOnChanges() will execute on every @Input() property change. If you want to execute any component method, based on the @Input() value change, then you should write such logic inside ngOnChanges() .

What runs before ngOnInit?

OnInit : ngOnInit is component's life cycle hook which runs first after constructor(default method) when the component is being initialized. So, Your constructor will be called first and Oninit will be called later after constructor method. You can check this small demo which shows an implementation of both things.


1 Answers

You cannot prevent this behavior, but you can:

Use a Subject :

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

Use a boolean property:

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

Use the SimpleChanges API

You can also check the SimpleChange.isFirstChange() method :

isFirstChange() : boolean Check whether the new value is the first value assigned.

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"     }   }  } 
like image 148
n00dl3 Avatar answered Oct 14 '22 11:10

n00dl3