Angular 2路由器 - 从代码命名路由器出口导航

时间:2017-06-13 09:12:01

标签: angular2-routing router-outlet

使用@ angular / router“:”3.4.7“。

建议的解决方案here不再有效。

      /**
        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 {

}

手动导航按预期工作

http://localhost:5000/app/build/#/product-module/product(正确显示指定商店中的概述组件)

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

(在指定的插座中正确显示详细信息组件)

问题

无法找出执行程序导航的正确方法:

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

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

发生以下错误:

错误:无法匹配任何路线。网址细分:'详情'。

2 个答案:

答案 0 :(得分:11)

您可以像这样以编程方式导航

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

注意:skipLocationChange用于隐藏地址栏中的网址。

参考官方文件:https://angular.io/guide/router

答案 1 :(得分:4)

您可以尝试相对导航

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

为此,您必须在组件中注入当前路由器快照和激活路由

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

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