簡體   English   中英

Angular 2使用組件屬性動態設置routerLink

[英]Angular 2 dynamically set routerLink using a component property

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

我的組件看起來鏈接這個:

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一切正常。 我的路由器配置似乎是正確的,因為當我直接添加到我的模板時,它也可以正常工作。 誰能幫我這個?

Grt Marco

你可以在html中使用這樣的代碼來動態創建url。

例如,您在路由器中的path:'destination/:id'path:'destination/:id'然后您可以像這樣使用routerLink

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

對於任何有這個問題的人使用Angular 2.4和

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

app.module.ts而不是ROUTER_DIRECTIVES (不再需要)中,以下語法對我ROUTER_DIRECTIVES

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

假設你的數組看起來像:

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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM