Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 788
Marco Avatar asked Jul 05 '16 12:07

Marco


1 Answers

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>
like image 124
MostafaMashayekhi Avatar answered Oct 19 '22 23:10

MostafaMashayekhi