Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

prevent reload component when switching in routes in Angular4

Tags:

angular

I have a page like:

enter image description here

There are two lables: A and B,when clicking A, the outlet will present component A, and component B is shown when clicking B.

Now the label B is clicked and the component B is presented, then click label A, and then click B, the component will raise a reload by ngOnInit. The question is:

How to prevent component B reloading when switching between A and B, I'd like to Init component B just once.

like image 657
Dante Jiang Avatar asked Nov 05 '25 05:11

Dante Jiang


2 Answers

If you don't want to reload components on changing the route why don't you simply put the components in the page and hide/show them accordingly? Please check this example that I created:

https://stackblitz.com/edit/angular-c2teek

like image 145
Bahman Avatar answered Nov 07 '25 04:11

Bahman


I have used angular service to maintain all the data of components and has called the relevant functions in component's constructor to assign those values to the component's local variables / objects.

So on every switch, the component's constructor will be invoked and it'll fetch the properties from the service.

You can do the same calling in ngOnInit() as well if not constructor.

like image 45
AmitKhiwal Avatar answered Nov 07 '25 05:11

AmitKhiwal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!