Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Angular Nested Child Routing

I am learning use of multiple router-outlet.

While using navigateBy function of router, i am not able to view my child route and getting error. But if i access it via routerLink in html i get the desired output.

So in below code, navigation to songs is working , but navigation to films is not.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const routes = [
  {
    path: 'bollywood',
    component: BollywoodComponent,
    children: [
      {
        path: 'films',
        component: FilmsComponent,
      },
      {
        path: 'songs',
        component: SongsComponent,
      },
    ],
  },
  {
    path: 'hollywood',
    component: HollywoodComponent,
  },
  {
    path: 'tollywood',
    component: TollywoodComponent
  },
];

App Component html

<button class="f-margin-16" (click)="navigateToBollywoodSection()"> Bollywood </button>
<button class="f-margin-16"  (click)="navigateToHollywoodSection()"> Hollywood </button>
<button class="f-margin-16" [routerLink]="['tollywood']" > Tollywood </button>

<br>
Router outlet starts now

<router-outlet> </router-outlet>

Bollywood Component html

<button (click)="navigateToFilms()"> Films </button>
<button [routerLink]="['songs']"> Songs </button>

<router-outlet> </router-outlet>
  navigateToFilms() {
    this.router.navigate(['/films']);
  }

StackBitz Link
https://stackblitz.com/edit/angular-ivy-1nzkus?file=src/app/bollywood/bollywood.component.html

>Solution :

In router.navigate, you can pass relativeTo as the second param.

navigateToFilms() {
    this.router.navigate(['/films'], {relativeTo: this.activatedRoute} );
}

This way navigation will happen relative to the current route.
In the constructor you can add the ActivatedRoute dependency.

constructor(private activatedRoute: ActivatedRoute) {}

If you use <button [routerLink]="['songs']"> Songs </button>, the navigation by default happens relative to the current route.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading