Angular 2 Router – named router-outlet navigation from code

angular2-routingrouter-outlet

Using @angular/router": "3.4.7".

Proposed solution here doesn't work anymore.

      /**
        The ProductComponent depending on the url displays one of two info 
         components rendered in a named outlet called 'productOutlet'.
       */
        @Component({
          selector: 'product',
          template: 
          ` <router-outlet></router-outlet>
            <router-outlet name="productOutlet"></router-outlet>
          `
        })
        export class ProductComponent{
         }
@NgModule({
  imports: [
    CommonModule,
    RouterModule.forChild([
          {
            path: 'product',
            component: ProductComponent,
            children: [
              {
                path: '',
                component: ProductOverviewComponent,
                outlet: 'productOutlet'},
              {
                path: 'details',
                component: ProductDetailsComponent,
                outlet: 'productOutlet' }
            ]
          }
      ]

    )],
  declarations: [
    ProductComponent,
    ProductHeaderComponent,
    ProductOverviewComponent,
    ProductDetailsComponent
  exports: [
    ProductComponent,
    ProductHeaderComponent,
    ProductOverviewComponent,
    ProductDetailsComponent
  ]
})
export class ProductModule {

}

Manual navigation works as expected

http://localhost:5000/app/build/#/product-module/product (correctly displays overview component in named outlet)

http://localhost:5000/app/build/#/product-module/product/(productOutlet:details)

(correctly displays details component in named outlet)

THE PROBLEM

Cannot figure out the correct way to perform programatical navigation:

this.router.navigateByUrl('/(productOutlet:details)');

this.router.navigate(['', { outlets: { productOutlet: 'details' } }]);

Following errors occur:

Error: Cannot match any routes. URL Segment: 'details'.

Best Answer

You can navigate programatically like this

this.router.navigate([{ outlets: { outletName: ['navigatingPath'] } }], { skipLocationChange: true });

Note: skipLocationChange is use to hide the url from the address bar.

Refer the official document : https://angular.io/guide/router

Related Topic