Search code examples
angulartypescriptrouterangular-routerangular-load-children

Parent component not hides in Angular router


I have an appComponent in which i display a toolbar, footer and the main content. This main content uses the router-outlet directive. It's something like this

<div class="h-100">
    <app-toolbar></app-toolbar>
    <app-breadcrumb></app-breadcrumb>
    <div class="container h-100">
      <router-outlet></router-outlet>
    </div>
</div>

in the toolbar I have a menu with some items. For example

<button [routerLink]="['/list']" routerLinkActiveOptions="{exact:true}">List</button>

When I click on the button I can show the content of that page (because of the router-outlet). I can now show a table with some content and it works fine. Now, I need to click on a row and show the detail of the row itself. To do that I'm just doing something like this

<a [routerLink]="['detail/',row.id]">{{value}}</a>

and in the same page of this table (I am using ngx-datatable) I have another <router-outlet></router-outlet>. In this way I can now show another component at the url ".../detail/0" for example. This is called DetailComponent. What's the problem? Everything works well expect for the parent component (the table) that still stays there. When I click a row, The table not disappears but stays there and just below it, the child component appears. This is my routes by the way

const routes: Routes = [
{
    path: 'list', 
    component: ListComponent, 
    canActivate : [AuthguardService], 
    children: [
      {
        path: 'detail/:id', component: DetailComponent, canActivate : [AuthguardService],
        data: {
          breadcrumb: ''
        }
      }
     ],
     data: {
      breadcrumb: 'List'
    } 
  },{
    path: '', redirectTo: '/home', pathMatch: 'full'
  },
  { path: '**', redirectTo: '' }
];

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

I tried also to remove <router-outlet></router-outlet> from the ListComponent but if I do that, the child component doesn't show

https://stackblitz.com/edit/angular-router-basic-example-n2uzis?file=app/views/details/detail.component.ts


Solution

  • This is the expected behavior with the current route setup.

    In order to fix it, there should be a wrapper component instead of the ListComponent, and list component should also be a child of it like DetailComponent.

    Components listed as children under a route do not make the parent component to disappear, parent will be the anchor and it's children will be rendered to where you place the router-outlet in the parent component.