Angular 2 路由 - 是否可以使用 ngFor 从路由中创建动态的 routerLinks?

4
我很愿意将特定模块中所有已定义路径的路由收集起来,然后使用ngFor循环它们,创建一个动态链接列表在我的组件HTML中。
ngFor示例(overview.component.html):
<li *ngFor="let item of items; let i = index;">
   <a routerLink="/{route.path}">{route.path}</a>
</li>

模块示例(base.module.ts):

...

const routerConfig = [
  {
    path: '',
    component: BaseComponent,
    children: [
      {
        path: '',
        component: OverviewComponent
      },
      {
        path: 'group-one',
        component: OverviewComponent
      },
      {
        path: 'group-one/:id',
        component: DetailComponent
      },
      {
        path: 'group-two',
        component: OverviewComponent
      },
      {
        path: 'group-two/:id',
        component: DetailComponent
      }
    ]
  }
];

@NgModule({
  imports: [
    RouterModule.forChild(routerConfig)
  ]
  ...
})
export class BaseModule { }

在尝试使用ActivatedRoute、Router等进行各种实验后,我没有找到一个可用于使用的包含此信息的对象。

目前是否可以通过Angular 2 Router实现这一点?

我该如何解决这个问题?


也许 router.config 会有所帮助。你可以尝试一下。 - developer033
通过 router.config[i].path 循环确实可以列出所有顶级路由,但是不能列出嵌套模块中的特定路由。你可能认为这应该可以通过 ActivatedRoute 在某个地方访问到... - dustintheweb
2
你尝试过 console.log(this.activatedRoute.routeConfig) 吗? - developer033
嗯,这下子可真是个好消息了……现在它出现在“子元素”下面了。也许我最初测试时没有使用子元素容器。感谢您的回复。 - dustintheweb
1个回答

3
这段代码。
<a routerLink="/{route.path}">

/{route.path}直接作为路由路径传递

你可能想要使用以下方式之一:

<a [routerLink]="'/' + route.path">

或者

<a routerLink="/{{route.path}}">

为了让Angular评估表达式,绑定必须只有一个[]{{}}(同时不能出现)。
[propName]="..."

或者

propName="{{...}}"

后者总是将结果字符串化,因此不适合传递对象。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接