Angular 2 Router - named router-outlet navigation from code

大城市里の小女人 提交于 2019-12-30 17:37:10

问题


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'.


回答1:


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




回答2:


You can try relative navigation as

this.router.navigate(['new'],{relativeTo:this.route})

For this you will have to inject current router snapshot and Activated route in component as

import { Router,ActivatedRoute } from "@angular/router";

constructor(private router:Router,private route:ActivatedRoute ){}


来源:https://stackoverflow.com/questions/44517100/angular-2-router-named-router-outlet-navigation-from-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!