Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force Angular2 to reload component on navigate

In Angular2 RC1 and lower calling a route link always causes a component to reload:

<a [routerLink]="['/page', {id: 1}]">A link </a>

Using Angular2, none RC, the component isn't reloaded if its navigating to itself with different parameters. Is there any way to get the reload behavior back?

I understand the other way of dealing with this, subscribing from the ActivatedRoute and detected variable changes, but this causes the component logic to increase in complexity.

like image 944
Luke Dupin Avatar asked Oct 21 '16 00:10

Luke Dupin


People also ask

Does router navigate reload the page?

The onSameUrlNavigation property defines what the router should do if it receives a navigation request to the current URL. By default, the router will ignore this navigation. However, this prevents features such as a “refresh” button.

Can we refresh a component in Angular?

If you are working with Angular and need to refresh a component without navigation on another component without using window. location. reload() or location.

Does the page reload when we navigate to another route react?

Just put that attribute on your Router, and whenever you are on a new Path it will force the page to reload itself. May be you are trying to push in history object, then bind your component with withrouter or use window. location. href = url to redirect ..


2 Answers

Although you've mentioned 'ActivatedRoute' and how it will complex your code, I think that this will help other people that are facing this problem when they're reaching your question, like me :) .

This topic will answer your question.

This code below (pasted from the topic above), is where the 'magic' is happening. If you'll place your 'reload' code in this subsribe function, your component will reload.

ngOnInit() {
   this.sub = this.route.params.subscribe(params => {
      this.id = +params['id']; // (+) converts string 'id' to a number
      // Some 'reload' coding
      // In a real app: dispatch action to load the details here.
   }); 
}
like image 149
benshabatnoam Avatar answered Oct 07 '22 04:10

benshabatnoam


A simple way to do this is to force the template to reload using *ngIf. You would need a variable that "turns the component off and on". If the values of variables have changed before this off/on behaviour, they will be rendered when the view is on again.

like image 40
mtsvr Avatar answered Oct 07 '22 04:10

mtsvr