4

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.

1
  • have you considered using resolvers? Commented Mar 14, 2018 at 6:58

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

6 Comments

Bad solution IMHO, drastically affects performances if components include heavy stuff.
@Sampgun I am not sure if I call this bad solution for the asked question. But I am happy to upvote your solution if you have better idea.
I don't have time to write an answer, right now, but basically using a Subject (in some factory) to save the last state for both routes would do the job. Also if I'm not mistaken it could possible to customize Angular routesReusingStrategy to achieve the same goal.
Here, something like this itnext.io/… (not tested, but I have to do something similar, so I will be able to update this question. I'll bookmark for the purpose.)
Thanks for sharing the link. I agree with you that we can use "RouteReuseStrategy" and it could be a better (fancier) solution. However, I am not clear how does it impact performance? The question is about calling ngOnInit of component B only one time and I am not sure if it makes any difference if we use "RouteReuseStrategy" or not.
|
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.