Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Routes not rendering child components, instead render parent component

I want to create a nested route movies/:id However with my current configuration, when user navigates to movies/1 the parent component is always rendered. I need MovieDetailComponent to render on movies/1 url. Here is my configuration:

const routes: Routes = [{
    path: '',
    component: HomeView
  },
  {
    path: 'movies',
    component: MoviesView,
    children: [{
      path: ':id',
      component: MovieDetailComponent
    }]
  },
  {
    path: 'not-found',
    component: PageNotFoundComponent,
    pathMatch: 'full'
  },
  {
    path: '**',
    redirectTo: 'not-found'
  }
];

I have tried adding pathMatch: 'full' to the parent component first and then child component, and then both. When I add pathMach: 'full' to the parent component, the child URL doesn't even get hit, when I add the pathMatch: 'full' just to the child component, only the parent component ever gets rendered even if the URL is /movies/:id Why is this happening?

When I moved the child path into its own route, not being nested, the component rendered correctly.

const routes: Routes = [{
    path: '',
    component: HomeView
  },
  {
    path: 'movies',
    component: MoviesView
  },
  {
    path: 'movies:id',
    component: MovieDetailComponent
  } {
    path: 'not-found',
    component: PageNotFoundComponent,
    pathMatch: 'full'
  },
  {
    path: '**',
    redirectTo: 'not-found'
  }
];
like image 214
O.MeeKoh Avatar asked Nov 30 '22 14:11

O.MeeKoh


1 Answers

If you have route that has a component and also a children field Angular will use that component's router outlet to place the children component DOM. So in your case you should have a router outlet in your MoviesView component:

<router-outlet></router-outlet>

If you want to have a different view when you go to movies and movies/:id you need to go with the second method. If you need now or in the future to have more than one extra route under the movies route I prefer to write it as

const routes: Routes = [
  { path: '', component: HomeView },  
  { path: 'movies',
    children: [
    { path: '', component: MoviesView }
    { path: ':id', component: MovieDetailComponent }
  ]},
  { path: 'not-found', component: PageNotFoundComponent, pathMatch: 'full' },
  { path: '**', redirectTo: 'not-found'}
];

Also if you don't need the movies route (without the id) you can do:

const routes: Routes = [
  { path: '', component: HomeView },  
  { path: 'movies',
    children: [
    { path: ':id', component: MovieDetailComponent }
  ]},
  { path: 'not-found', component: PageNotFoundComponent, pathMatch: 'full' },
  { path: '**', redirectTo: 'not-found'}
];
like image 56
Zoltán Szepesi Avatar answered Dec 10 '22 02:12

Zoltán Szepesi