Angular 2如何使用组件属性动态设置路由链接

8
我创建了一个组件,其中包含一个带有routerLink属性的a元素,我想从使用该组件的模板中设置它。当我尝试这样做时,我会收到“无法读取未定义属性'path'”的错误消息。

我的组件如下所示:

info-box.component.ts

import { Input, Component } from "@angular/core";
import { ROUTER_DIRECTIVES } from "@angular/router";

@Component({
    selector: "info-box",
    template: require("./info-box.component.html"),
    directives: [
        ROUTER_DIRECTIVES
    ]
})

export class InfoBoxComponent {
    @Input() routerLink: string;
    @Input() imageUrl: string;
}

info-box.component.html

<a [routerLink]="[routerLink]"> 
    <img src="{{imageUrl}}" width="304" height="236">
</a>

在使用该组件的模板中,它看起来像这样:

<info-box [routerLink]="['/test']" [imageUrl]="['./testimage.jpg']"

如果我不添加routerLink,一切都正常。我的路由器配置似乎也是正确的,因为当我直接将标签添加到模板中时,它也可以正常工作。有人能帮助我解决这个问题吗?
谢谢,Marco

1
看起来类似于 https://github.com/angular/angular/issues/9801 - Günter Zöchbauer
3个回答

15

您可以在HTML中使用以下代码来动态创建链接。例如,如果您的路由路径为path:'destination/:id',那么您可以像这样使用routerLink

<div *ngFor = "let item of items">
 <a routerLink = "/destination/{{item.id}}"></a>
</div>

6
对于使用 Angular 2.4 并与以下内容同时出现问题的任何人:
``` import { AppRoutingModule } from './app-routing.module'; ```
在 `app.module.ts` 中,不再需要 `ROUTER_DIRECTIVES`,以下语法对我有效:
<a [routerLink]="['item', item.id ]">Item</a>

1
假设你的数组长这样:
this.menuuItems = [
  {
    text: 'Tournament Setup',
    path: 'app-tournament'
  }];

现在在你的HTML中使用类似于

的标签。
<li *ngFor = "let menu of menuuItems">
     <span routerLink="/{{menu.path}}">
      <a>{{menu.text}}</a>
    </span>
    </li>

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