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.
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.
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.
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() .
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.
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
APIYou 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" } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With