Dynamic Nested router-outlet usage in Angular 4

Issue

Dynamic Nested router-outlet usage in Angular 4

I had simple Angular CLI with dynamic routing with angular.

In my application, I had 2 different page like home and about. In that Home, I want to insert more topics with dynamic contents. so I had included nested router inside the home page. while navigating nested content it’s replacing with the root element. I have attached the online sample, please check that. can anyone please provide a solution for that.

online Sample

Router configurations

    import { Routes } from '@angular/router';

import { AboutComponent } from './about/about.component';
import { HomeComponent } from './home/home.component';
import { HomeNestComponent } from './home/homenest/homenest.component';

export const rootRouterConfig: Routes = [
  { path: 'home', component: HomeComponent },
  { path: 'about', component: AboutComponent },
  { path: 'home/homenest', component: HomeNestComponent },

];

Solution

Do the following changes in Router configurations.

  import { Routes } from '@angular/router';
     import { AboutComponent } from './about/about.component';
    import { HomeComponent } from './home/home.component';
    import { HomeNestComponent } from './home/homenest/homenest.component';

    export const rootRouterConfig: Routes = [
      { path: 'home', component: HomeComponent, 
        children:[{ path: 'homenest', component: HomeNestComponent }]
      },
      { path: 'about', component: AboutComponent },
      { path: 'homenest', component: HomeNestComponent },

    ];

Changes in home.component.ts.

public homeNestClick(e) {
          this.router.navigateByUrl('/home/homenest');
      }

https://stackblitz.com/edit/angular-tf7ru3?file=src/app/home/home.component.ts

Answered By – Amar Kaygude

Answer Checked By – Jay B. (AngularFixing Admin)

Leave a Reply

Your email address will not be published.