Angular 2使用组件属性动态设置routerLink [英] Angular 2 dynamically set routerLink using a component property

查看:108
本文介绍了Angular 2使用组件属性动态设置routerLink的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个组件,其中包含一个带有routerLink属性的元素,我想从使用该组件的模板中对其进行设置.当我尝试执行此操作时,出现错误消息无法读取未定义的属性"路径".

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. 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']"

如果我不添加routerLink,一切正常.我的路由器配置似乎正确,因为当我直接将其添加到模板中时,它也可以正常工作.有人可以帮我吗?

If I do not add the routerLink everything works fine. 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

推荐答案

您可以使用类似的代码在html中动态创建网址.

You can use code like this for dynamic create url in html.

例如,您在路由器中的路径为path:'destination/:id',那么您可以像这样使用routerLink:

For example, your path in router is path:'destination/:id' then you can use routerLink like this:

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

这篇关于Angular 2使用组件属性动态设置routerLink的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆