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

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

问题描述

我创建了一个组件,其中包含一个具有 routerLink 属性的元素,我想从使用该组件的模板中设置该属性.当我尝试这样做时,我收到错误消息无法读取未定义的属性‘路径’".

我的组件看起来链接了这个:

info-box.component.ts

import { Input, Component } from "@angular/core";从@angular/router"导入 { ROUTER_DIRECTIVES };@成分({选择器:信息框",模板:需要(./info-box.component.html"),指令:[ROUTER_DIRECIVES]})导出类 InfoBoxComponent {@Input() 路由器链接:字符串;@Input() imageUrl: 字符串;}

info-box.component.html

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

以及使用组件的模板如下所示:

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

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

马可哥

您可以使用这样的代码在 html 中动态创建 url.

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

<a routerLink = "/destination/{{item.id}}"></a>

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

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>

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. 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

解决方案

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

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天全站免登陆