'Avoid ngOnChanges until ngOnInit is completed in Angular
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 ??
Solution 1:[1]
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
Solution 2:[2]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Dibyanshu Banerjee |
| Solution 2 | Bryan BERGER |
