Angular 2 dynamically set routerLink using a component property

ε祈祈猫儿з 提交于 2020-01-24 03:45:33

问题


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


回答1:


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>



回答2:


For anyone having this problem using Angular 2.4 in conjunction with

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:

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



回答3:


suppose your array looks like :

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

now in your html use like

<li *ngFor = "let menu of menuuItems">
     <span routerLink="/{{menu.path}}">
      <a>{{menu.text}}</a>
    </span>
    </li>


来源:https://stackoverflow.com/questions/38203726/angular-2-dynamically-set-routerlink-using-a-component-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!