Reputation: 1109
I am facing a strange issue in my Angular 4 project. I am trying to navigate to a path through code (on button click). I am using router.navigate()
method as follows to accomplish the job --
this._router.navigate(["/employeeDetails", selectedEmployee.EmployeeId]);
Where selectedEmployee.EmployeeId
is a number.
The navigation happens but I am getting a very weird thing in the URL. Initially the URL shows as follows --
http://localhost:4200/?employeeDetails/170
and then the ?
sign vanishes from the URL and the required page is loaded.
Can anyone please tell me why the ?
sign is coming in the URL. Ideally it should load the respective component for the route "/employeeDetails"
without refreshing the page. I also tried the code without /
as follows but no help.
this._router.navigate(["/employeeDetails", selectedEmployee.EmployeeId]);
Any help would be appreciated.
Upvotes: 6
Views: 6175
Reputation: 3276
None of the previous answer gives the correct answer even thought some of them work! But all put a patch without acting on the cause of the event we have.
The solution is to set the type="button" to the button element, because by default the form identifies the button as type="submit" if not specified and triggers the submit action.
However thanks because the combination of the answers helped me to find the real cause!
Upvotes: 13
Reputation: 111
I had the same problem. Solved it by adding this action to my form tag:
<form action="javascript:void(0)"
Upvotes: 3
Reputation: 10135
To have que question mark in URL with angular 2 (4,5,6) for parameters:
this.router.navigate(['/companie'], { queryParams: { type: 'firstRegister' }});
you will get:
https://myurl/#/companie?type=firstRegister
To have the classic parameter, it is:
this.router.navigate(['/companie', { type: 'firstRegister' }])
you will get:
https://myurl/#/companie;type=firstRegister
Upvotes: 4
Reputation: 54
Reason could be a missing action="/formsubmit"
. When Chrome tries to send a GET request without it this it appends a ?
to the current URL.
Try the below for your submit action:
onSubmitAction(event){
event.preventDefault()
}
Hope it helps :)
Upvotes: 3
Reputation: 11696
Be sure that your injected _router: Router
in your components constructor like this:
constructor(private _router: Router) {}
Change this:
this._router.navigate(["/employeeDetails", selectedEmployee.EmployeeId]);
to this:
this._router.navigate(['/employeeDetails', selectedEmployee.EmployeeId]);
or this:
this._router.navigate(['/employeeDetails/' + selectedEmployee.EmployeeId]);
In your routing file you should have something like this:
const routes: Routes = [
...
{ path: 'employeeDetails/:id', component: YourComponent },
...
];
Upvotes: 1