4

我已經創建了一個組件,該組件包含一個帶有我想從使用組件的模板中設置的routerLink屬性的元素。當我嘗試這樣做時,我收到錯誤消息「無法讀取屬性」路徑'未定義'。Angular 2使用組件屬性動態設置routerLink

我的部件查看此鏈接:

信息,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; 
} 

信息,box.component.html

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

而且和模板在組分使用它看起來像這樣:

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

如果我不添加routerLink,一切正常。我的路由器配置似乎是正確的,因爲當我直接添加到我的模板它也可以正常工作。誰能幫我這個?

石榴石馬爾科

+1

類似於https://github.com/angular/angular/issues/9801 –

回答

7

,你可以在HTML中使用如下代碼動態創建的URL

例如你的路由器的路徑是path:'destination/:id'那麼你可以使用routerLink這樣

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

我希望我的回答很有用

+0

工作!非常感謝! – Diego

2

對於使用Angular 2.4和

import { AppRoutingModule } from './app-routing.module';

app.module.ts而不是 ROUTER_DIRECTIVES,它不再需要

,下面的語法爲我工作:

<a [routerLink]="['item', item.id ]">Item</a>