Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 router.navigate refresh page

This is how the routes and component look like:

routes.config

export const routes: RouterConfig = [    { path: 'users', component: UsersComponent, canActivate: [AuthGuard] },       { path: 'users/new', component: NewUserComponent },     ]; 

new-user.component

 addField(newName: string){         this.items.push({            name: newName,       })       this._router.navigate(['/users']) 

Is Angular2 supposed to refresh the page on router.navigate?

What else to use instead of router.navigate to avoid any page refresh?

Here is the proof: enter image description here

like image 303
Cristian Muscalu Avatar asked Jun 30 '16 10:06

Cristian Muscalu


People also ask

Does router navigate refresh page?

All it does is store current url then navigates to the application root and back to current url forcing a reload.

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

react-router-dom allows us to navigate through different pages on our app with/without refreshing the entire component. By default, BrowserRouter in react-router-dom will not refresh the entire page.


1 Answers

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> 
like image 170
ElSnakeO Avatar answered Oct 15 '22 15:10

ElSnakeO