Scenario : I have two components Parent
and Child
. Both components have some API calls being done in ngOnInit
. Child component has ngOnChanges
lifecycle hook.
On page load based on certain conditions I'm triggering child's ngOnChanges
from Parent component by changing the @Input parameter being passed to Child
.
Issue : Child component's ngOnChanges
is being triggered from Parent
component before the Child component's ngOnInit
is completed.
How to avoid this ??
CodePudding user response:
Assuming from parent component once your ngOninit api call completes you will be updating the input variable for child component.
You can check a condition in child components ngOnchanges :
ngOnChanges(changes: import("@angular/core").SimpleChanges): void {
//reLoad: Boolean type input parameter comming from parent component
if (changes['reLoad'] && (changes['reLoad'].previousValue !== changes['reLoad'].currentValue)) {
if (changes['reLoad'].currentValue) {
//Call load method of child component
this.childApiLoad();
}
}
}
- It's a default behavior of Angular component, ngOnChanges lifecycle hook will invoke first and than ngOnInit. https://angular.io/guide/lifecycle-hooks
CodePudding user response:
Try ngDoCheck()
instead of ngOnChanges()
. It could resolve your problem because it is triggered after ngOnInit()
.
Docs here: https://angular.io/guide/lifecycle-hooks#lifecycle-event-sequence