【问题标题】:Angular 2 Routes - Is it possible to create dynamic routerLinks from routes, using an ngFor?Angular 2 Routes - 是否可以使用 ngFor 从路由创建动态 routerLink?
【发布时间】:2017-06-22 17:44:36
【问题描述】:

我想获取具有定义路径的特定模块中的所有路由,并使用 ngFor 循环它们并在我的组件 html 中创建动态链接列表。

ng例如(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.config 会有所帮助。你可以玩这个。
  • @developer033 循环通过 router.config[i].path 确实列出了所有顶级路由,但没有特定于嵌套模块的路由。您会认为这可以通过 ActivatedRoute 某处访问...
  • 你试过console.log(this.activatedRoute.routeConfig)吗?
  • 好儿子……它现在出现在“孩子”下。当我第一次测试这个时,也许最初我没有使用 children 容器。感谢您的回复。

标签: javascript angular routes angular2-routing


【解决方案1】:

这段代码

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

通过/{route.path} 字面上作为路由路径

你可能想要

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

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

要让 Angular 评估表达式,绑定需要恰好具有 []{{}} 之一(永远不要同时使用两者)

[propName]="..."

propName="{{...}}"

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-13
    • 2017-08-26
    • 1970-01-01
    • 1970-01-01
    • 2020-03-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多