Angular2 application router.navigate reloads

I have the following routes defined in my application ...

app.components.ts @RouteConfig([ {path:'/employees/...', name:'Employees', component:EmployeeComponent}, ... employee.component.ts @RouteConfig([ {path:'/', name:'EmployeeList', component:EmployeeListComponent, useAsDefault: true}, {path:'/:id', name:'EmployeeDetail', component:EmployeeDetailComponent} ]) 

When I head from EmployeeDetailComponent ...

 <button class="btn btn-default" [routerLink]="['EmployeeList']">Close</button> 

attach routes to the employee list page, as expected.

However, when I route using router.navigate ...

 // template <button class="btn btn-default" (click)="save()">Save</button> // EmployeeDetailComponent saveEmployee() { this._employeeServer.updateEmployee(this.employee); this._router.navigate(['EmployeeList']); } 

the application sends a list of employees (as expected), and then, after a few moments, the application restarts completely (not as expected).

Any idea why router.navigate behaves differently than routerLink? What am I missing?

+7
angular angular2-routing
source share
3 answers

You can use this directive:

 @Directive({ selector: `click-stop-propagation` events: 'stopClick($event)' }) class ClickStopPropagation { stopClick(event:Event) { event.preventDefault(); event.stopPropagation(); } } 

and apply it as follows:

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

Another solution would be to pass the event to the save method:

 <button class="btn btn-default" (click)="save($event)" click-stop-propagation>Save</button> 

and use it to stop the event from spreading:

 save(event) { this._employeeServer.updateEmployee(this.employee); this._router.navigate(['EmployeeList']); event.preventDefault(); event.stopPropagation(); } 
+6
source share

<button> inside the <form> may try to send. Try adding <button type="button"> to prevent sending when the button is clicked.

+9
source share

While Thierry's answer with canceling the distribution of the event worked for me, I found another solution:

Try moving the navigation to a timeout (of any duration)

 ... setTimeout(() => { this._router.navigate(['EmployeeList']); }, 0); ... 

Do you think this is more accurate than including a click event for discussion. For me, I wanted to postpone the navigation to wait for the animation anyway, and this way saved me from turning on an extra click event.

+1
source share

All Articles