简体   繁体   English

Angular 2使用组件属性动态设置routerLink

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

I have created an component that contains a element with a routerLink property which I want to set from a template that uses the component. 我创建了一个组件,其中包含一个带有routerLink属性的元素,我想从使用该组件的模板中设置该属性。 When I try to do this I get the error message 'Cannot read property 'path' of undefined'. 当我尝试这样做时,我收到错误消息'无法读取属性'未定义'的路径'。

My component looks link this: 我的组件看起来链接这个:

info-box.component.ts 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 INFO-box.component.html

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

And and the template where the component is used it looks like this: 并且使用组件的模板看起来像这样:

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

If I do not add the routerLink everything works fine. 如果我不添加routerLink一切正常。 My router config als seems to be right because when I add the directly to my template it also works fine. 我的路由器配置似乎是正确的,因为当我直接添加到我的模板时,它也可以正常工作。 Can anyone help me with this? 谁能帮我这个?

Grt Marco Grt Marco

You can use code like this for dynamic create url in html. 你可以在html中使用这样的代码来动态创建url。

For example, your path in router is path:'destination/:id' then you can use routerLink like this: 例如,您在路由器中的path:'destination/:id'path:'destination/:id'然后您可以像这样使用routerLink

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

For anyone having this problem using Angular 2.4 in conjunction with 对于任何有这个问题的人使用Angular 2.4和

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

in the app.module.ts instead of ROUTER_DIRECTIVES , which is no longer needed, the following syntax worked for me: app.module.ts而不是ROUTER_DIRECTIVES (不再需要)中,以下语法对我ROUTER_DIRECTIVES

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

suppose your array looks like : 假设你的数组看起来像:

this.menuuItems = [
  {
    text: 'Tournament Setup',
    path: 'app-tournament'
  }];

now in your html use like 现在在你的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