angular - how to stop ngOnChanges Called before ngOnInit() -
in angular application, came situation ngonchanges should called when inputs bound changes. so, there way stop execution of ngonchanges before ngoninit. there way accomplish this. in advance.
you cannot prevent behavior, can:
use subject :
class foo implements onchanges,oninit{ onchanges = new subject<simplechanges>(); ngoninit(){ this.onchanges.subscribe((data:simplechanges)=>{ // when inited }); } ngonchanges(changes:simplechanges){ this.onchanges.next(changes); } } use boolean property:
class foo implements onchanges,oninit{ initialized=false; ngoninit(){ // stuff this.initialized = true; } ngonchanges(changes:simplechanges){ if(this.initialized){ // stuff when ngoninit has been called } } } use simplechanges api
you can check simplechange.isfirstchange() method :
isfirstchange() : booleancheck whether new value first value assigned.
class foo implements onchanges,oninit{ @input() bar:any; ngoninit(){ // stuff this.initialized = true; } ngonchanges(changes:simplechanges){ if(!changes["bar"].isfirstchange()){ // stuff if not initialization of "bar" } } }
Comments
Post a Comment