Please have a look at the Stackblitz Editor link. I've set up one angular application.
Brief working overview of the angular app
- Two components i.e app-component and child-component
- Initially, child component not display. There is a button in the parent app component when we click on the button, we enable one variable 'this.showChildComponent = true'.
- child component controlled by the variable this.showChildComponent.
- I'm using the 'firstParam' and 'secondParam' as a variable and sending these variables values to the child component.
Now, Please have a look at the issue
When we click on the button as I explained above, child component mounted and ngOnInit method will be called, you can also check the message on the console screen 'ngOnInit called: child component' but if I again click on the button, then the child component not re-render again and thus, ngOnInit method of child component not called.
// This method is defined in the app-component (parent) and it is called when user clicks on
// button
showChild() {
if (this.showChildComponent)
{
this.showChildComponent = false;
}
this.showChildComponent = true;
// child component ngOnInit call when
// I use the timer
// setTimeout(()=> {this.showChildComponent = true;}, 10);
this.firstParam = 'first param from parent';
this.secondParam = 'second param from parent';
}
// Parent component - app-component
<button (click)="showChild()">Click here to display the child component</button>
<div *ngIf="showChildComponent">
<app-child-component
[first_param]="firstParam"
[second_param]="secondParam"
></app-child-component>
</div>
As you can see in the code, if I use the setTimeout then child component ngOnInit method will be called whenever I click on the parent component button. But I don't want to use the timer here, what is the alternative solution to resolve this issue? whenever user clicks on the button, ngOnInit method of child component should be call.