Search code examples
angulartypescriptangular-routing

Angular routing just appending to url not going to new page


I am just trying to link when I click on an object in my home component that it brings me to the player detail component. I send in the method with all the data is sent correctly but it just appends to the url instead of actually going to the new page itself.

I also don't know where I should put the because it ends up constantly trying to render the player detail page if I have it in any component.

app-routing.module

import { NgModule } from "@angular/core";
import { Routes, RouterModule } from "@angular/router";
import { PlayerDetailComponent } from "./components/player-detail/player-detail.component";

const routes: Routes = [
  {
    path: "details/:playerID/:firstName/:lastName/:teamID",
    component: PlayerDetailComponent
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule {}

my home.component.ts

showDetails(
    playerID: String,
    firstName: String,
    lastName: String,
    teamID: String
  ) {
    this.router.navigate(["/details", playerID, firstName, lastName, teamID]);
  }

EDIT

I changed the app-routing to this

import { NgModule } from "@angular/core";
import { Routes, RouterModule } from "@angular/router";
import { HomeComponent } from "./components/home/home.component";
import { PlayerDetailComponent } from "./components/player-detail/player-detail.component";

const routes: Routes = [
  {
    path: "",
    component: HomeComponent
  },
  {
    path: "details/:playerID/:firstName/:lastName/:teamID",
    component: PlayerDetailComponent
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule {}

And my app component html is just this

<div class="main-container">
  <div>
    <router-outlet></router-outlet>
  </div>
</div>

This works but I really don't get why and what if I wanted to add a button back to the home page how would I do that now?

EDIT 2

I realized I just have to do '' if I want to go back to the home page.


Solution

  • You generally have some type of navigation outside the router-outlet to navigate to different components. All you components will render in the router-outlet and you can use the navigation to navigate to different features.

    Also you may not want to pass all your player details with path params but instead use a shared/central service to store your data and let your components access that data through the service. An example is when you go to player details, just use the player id as a path param then pull that players details from the central service.

    I put together an stackblitz example of a possible structure for the application.

    https://stackblitz.com/edit/angular-wm6pdm