Angular2 router.navigate refresh page

余生长醉 提交于 2019-11-27 01:57:00
ElSnakeO

You are probably calling the router.navigate function inside a click event.

<button class="btn btn-default"     (click)="save()">Save</button> 

And the save function being something like

save() {     //Do stuff     this._router.navigate(['/users', { id: userId } ]); } 

This works on IE11 and Edge browsers, but would reload the application in Chrome.

This is because of a missing type in the button element, if the button is inside a <form></form> Chrome will use 'submit' as it's default value. Causing a form submit when the button is clicked.

It's preferred to always set a type when using the button element See here:

So changing the HTML to

<button class="btn btn-default" type="button"         (click)="save()">Save</button> 

Will make it work on all 3 browsers.

My previous solution also works, (By returning false it would prevent the default action. a.k.a. submitting the form) but I think the above one is preferred.

Obsolete answer but kept for posterity:

<button class="btn btn-default"         (click)="save(); false">Save</button> 

I had the same effect (page refresh when navigating to details page) using a simple <a href="/details/1"></a> link. The solution was to use the angular link: <a [routerLink]="['/details', 1]"></a>

For me works nice (from component code):

window.location.href = "/sth"; 

it automatically reloads page to given url part.

I know its simple method but you can also set this code to refresh route on success event after all operation finished.

window.open('users', '_self');

It will reload and redirect to user page.

This covers an AngularJS/Angular hybrid situation. I'm adding the answer because this question is one of the top results when you google angular router page reload issues. Hopefully it'll save somebody else time.

In my case I had a very simple Angular 2 (actually 5) route configuration that mostly worked except for one case where a link from one route to another would inexplicably cause a page reload. I had checked for all the usual suspects, form, submit button, etc.

It turned out that somewhere in an AngularJS component that was displayed at the time the link was clicked, there was an ng-include. The documentation warns about this for a reason I guess. Reshuffled the template so the ng-include could be changed to a templateUrl and all was well.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!